【问题标题】:Laravel - get related modelLaravel - 获取相关模型
【发布时间】:2018-10-12 19:43:04
【问题描述】:

我正在使用构建查询的代码:

$products = \App\Product::where('id', '>', 0);

然后继续将其他相关模型添加到$product,具体取决于提供的参数。

我想在第一行代码中添加一个相关模型。但我显然做错了什么。

我尝试通过添加:->get()->designer 来添加“设计师”关系,如下所示:

  return json_encode($products = \App\Product::where('id', '>', 0)
        ->get()->designer);

给出错误:Property [designer] does not exist on this collection instance.

切换顺序也不起作用:->designer->get()); (我得到Undefined property)

我的Product模型有方法:

public function designer() {
        return $this->belongsTo('App\Designer');
    }

Product 表有一个“designer_id”列(它是一个“belongsTo”关系,所以我猜 Designer_id 应该在 Product 模型上)。

文档说:“我们可以访问关系方法,就好像它们被定义为模型上的属性一样”:$comments = App\Post::find(1)->comments;

我做错了什么?

【问题讨论】:

    标签: laravel-5 eloquent


    【解决方案1】:
    1. $products = \App\Product::where('id', '>', 0) ->get()->设计师;

    你的这行代码是错误的;我猜你们的关系是一对多的,这意味着一个设计师有很多产品,一个产品属于一个设计师。

    对比laravel文档[cmets and post]的例子,post有很多cmets,一个评论属于一个post。

    当你执行这一行时: $products = \App\Product::where('id', '>', 0)->get()

    laravel 将返回给你一个产品对象的集合,这意味着你无法通过产品集合找到设计师,因为你的产品模型中有 belongsTo 关系。

    你的问题的解决方案是像这样使用with eloquent 的助手:

    $products = App\Product::with('designer')->where('id', '>', 0)->get();
    

    在 laravel 社区中,我们将其命名为

    Eager Loading 技术可避免 n+1 个请求。

    你可以在这里找到更多信息Eager Loading

    之后,当你想获得设计师属性时,你可以像这样访问它们:

       foreach ($products as $product) {
        echo $product->designer->name;
    } 
    

    【讨论】:

    • 我之前在搜索“with”函数,但在文档中找不到它,所以我认为这是一个已弃用的东西......所以在这种情况下它非常重要。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2016-05-26
    • 2016-08-30
    • 2014-12-05
    • 2014-02-12
    • 2020-03-22
    • 2019-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多