【问题标题】:How to establish a dynamic model relationship in Laravel?如何在 Laravel 中建立动态模型关系?
【发布时间】:2021-02-14 20:54:11
【问题描述】:

我需要建立动态关系,但我做不到。

表格设计如下。

页表

id title
1 Hello world
2 Contact

分类表

id title
1 Electronics
2 Sports

博客表

id title
1 First blog

链接类型

id name
1 Page
2 Category
3 Blog

链接表

id type_id relation_id slug
1 1 1 page/hello-world
2 1 2 page/contact
3 2 1 category/electronics
3 2 2 category/sports
3 3 1 blog/first-blog

代码

控制器:

$links = Links::with('title')->get();

return response()->json($links);

// I need to get the "title" key.

链接模型:

public function title() {
    switch($this->type_id) {
        case '1':
            return $this->hasOne(Page::class, 'id', 'relation_id');
            break;
        case '2':
            return $this->hasOne(Category::class, 'id', 'relation_id');
            break;
        case '3':
            return $this->hasOne(Blog::class, 'id', 'relation_id');
            break;
    }
}

此状态不起作用,因为模型尚未形成。

错误输出

Call to a member function addEagerConstraints() on null

我应该怎么做?

谢谢。

【问题讨论】:

  • 刚刚注意到,但在您的switch() 中,每个案例都应返回belongsTo(Class::class, 'relation_id'); 而不是hasOne
  • $this->type_id 总是显示为空。可能是因为尚未创建查询。

标签: laravel


【解决方案1】:

你正在做的事情可以通过使用多态关系来实现。

pages
    id - integer
    name - string

categories
    id - integer
    title - string

blogs
    id - integer
    title - string

link_types
    id - integer
    name - string

links
    id - integer
    link_type_id - integer
    linkable_id - integer
    linkable_type - string

PageCategoryBlog 模型应该定义这些关系

public function link_types()
{
    return $this->morphToMany(LinkType::class, 'linkable', 'links')->using(Link::class);
}

public function links()
{
    return $this->morphMany(Link::class, 'linkable')
}

LinkType 模型应该定义这些关系

public function pages()
{
    return $this->morphedByMany(Page::class, 'linkable', 'links')->using(Link::class);
}

public function categories()
{
    return $this->morphedByMany(Category::class, 'linkable', 'links')->using(Link::class);
}

public function blogs()
{
    return $this->morphedByMany(Blog::class, 'linkable', 'links')->using(Link::class);
}

Link 模型应该定义这些关系

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Relations\MorphPivot;

class Link extends MorphPivot
{
    /**
     * Get the parent linkable model (blog, category, page).
     */
    public function linkable()
    {
        return $this->morphTo();
    }

    public function link_type()
    {
        return $this->belongsTo(LinkType::class, 'link_type_id');
    }
}
$link = Link::with('linkable')->first();

$link->linkable->title;

【讨论】:

  • 我需要能够在 JSON 输出中提供“title”键常量。由于会输出 JSON,我没有机会调用关系。
  • 使用多态一对多怎么样?我已经编辑了答案。
  • 试图获取非对象的属性“标题”。当我调试它不运行 SQL 查询。因此,没有收到任何数据。
猜你喜欢
  • 2021-03-23
  • 2022-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-04
  • 1970-01-01
  • 1970-01-01
  • 2019-11-14
相关资源
最近更新 更多