【问题标题】:Can I join a related table using Lauravel/Eloquent eager loading?我可以使用 Laravel/Eloquent 急切加载加入相关表吗?
【发布时间】:2014-08-08 07:52:42
【问题描述】:

我无法理解快速加载如何与 Lauravel/Eloquent 一起工作。我想抓住所有客户,和他们一起做一些事情,然后输出他们的brand_name。我有这些表:

    Clients
+-------------------+
| Field             |
+-------------------+
| client_id         |
| client_name       |
| client_brand_id   |
+-------------------+

    Brands
+-------------------+
| Field             |
+-------------------+
| brand_id          |
| brand_name        |
+-------------------+  

在客户端模型中我有关系:

public function brand()
{
    return $this->hasOne('Brand', 'client_brand_id', 'brand_id');
}

与品牌模型相反:

public function clients()
{
    return $this->hasMany('Client', 'brand_id', 'client_brand_id');
}

我想这样做,但它不起作用:

foreach( Client::with( 'brand' )->get( array('client_id', 'client_name' ) ) as $client ){
    echo $client->brand->brand_name;
}

【问题讨论】:

  • 你缺少array()的右括号
  • @hjpotter92 已修复,是我在帖子中的拼写错误。

标签: php mysql laravel eloquent


【解决方案1】:

您需要像这样在 client 模型中定义您的 brand 关系:

public function brand()
{
    return $this->belongsTo('Brand', 'client_brand_id', 'brand_id');
}

原因是客户和品牌之间是一对多的关系,而不是一对一的关系。

此外,您需要获取完整的模型以使预先加载的关系可用,如下所示:

foreach( Client::with( 'brand' )->get() as $client )
{
    echo $client->brand->brand_name;
}

【讨论】:

  • 完美,感谢您添加对完整模型的需求。我什至没想到!
  • 您需要与关系相关的所有键(外键和主键),不一定是完整的模型。
  • @JarekTkaczyk_deczo_ 要做到这一点,您需要在模型中选择外键/主键,具体正确吗?这限制了模型用于其他应用程序。将键添加到 get() 调用中的数组不起作用,构建的查询尝试从客户表中选择字段而不加入品牌表。
  • @RyanFisher 我不明白你在模型中的意思。无论如何,它不会到达get(使用get(),它会选择所有字段),因为with 会调用另一个查询。话虽如此,您需要在 with 调用中使用闭包,并在该闭包中使用 select
最近更新 更多