【问题标题】:Get Attributes Through One to One Pivot Table in Laravel 5.4通过 Laravel 5.4 中的一对一数据透视表获取属性
【发布时间】:2017-10-18 02:19:28
【问题描述】:

我有一个名为 Category 的模型。一个类别可以有多个主题。一个主题只能使用一个框架。但是一个框架可以被多个主题使用。

我的控制器方法:

    $category = Category::find(1);

    foreach ($category->themes as $theme) {

    }


    return response()->json(['category' => $category]);

输出:

 category: {
        id: 1,
        name: "DemoCategory",
        created_at: null,
        updated_at: null,
        themes: [
        {
        id: 1,
        frame_id: 1,
        created_at: null,
        updated_at: null,
        pivot: {
        category_id: 1,
        theme_id: 1
        }
       }
      ]
    }

主题模型:

public function categories()
{
    return $this->belongsToMany('App\Category', 'category_theme');
}

public function frame()
{
    return $this->hasOne('App\Frame', 'theme_frame');
}

框架型号:

empty

如何通过数据透视表连接主题和框架?

如您所见,主题嵌套在 JSON 对象中。但我也希望特定主题的框架嵌套在 JSON 对象中。 Frame 和 Theme 通过数据透视表具有一对一的关系。但正如您所看到的,它只返回 id 而不是整个对象。如何让 Frame 对象嵌套在 JSON 对象内的特定主题中?

【问题讨论】:

  • 一个问题是为什么你希望一对一的关系有一个数据透视表?
  • 我认为hasOne 仅适用于1-1 关系。我希望主题为belongTo 一个框架,框架为hasMany 主题。
  • @apokryfos - 谢谢。我想太多了。

标签: database laravel eloquent relationship one-to-one


【解决方案1】:

你不需要使用循环,你可以预先加载关系。

// with only themes
$category = Category::with('themes')->find(1);

//with themes and frame
$category = Category::with('themes.frame')->find(1);

https://laravel.com/docs/5.4/eloquent-relationships#eager-loading

【讨论】:

    【解决方案2】:

    快速回答是定义两个公共变量,每个模型一个,或者在查询中使用 with() 方法,如下所示:

    类别模型:

    public $with = ['themes'];
    

    主题模型:

    public $with = ['frame'];
    

    现在,每当您加载 category 模型(如 Category::first();)时,您还将加载与其关联的 themes,并且对于每个 theme,您将加载与该主题关联的 frame,希望如此就是你要找的。​​p>

    【讨论】:

    • 另请注意,这会每次都急切地加载您的关系。如果这是您想要的结果,那很好,但如果不是,这将在每次提取时不必要地加载关系。
    • 没错,这就是我在加载类别模型时说的原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    • 2021-09-10
    • 2018-06-08
    • 2018-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多