Laravel : 使用模型关系合并两个表
Laravel : Combine two tables using Model relations
我有两个表 :: shops
和 attachments
。商店有商店的所有详细信息和附件,以及商店的所有图片,ref_id
作为 FK。
现在对于移动应用程序,我必须列出带有商店标题和一张图片的商店。我可以使用 leftjoin 实现它,如下所示。
Shop::select('shops.name as shop_name','attachments.name as picture')
->leftjoin('attachments','attachments.ref_id','=','shops.shop_id')
->paginate(10);
这个returns只是店名和图片,
我想使用我不确定该怎么做的关系来获得相同的结果。有人可以就此给我建议吗
编辑
店铺模型
public function attachments(){
return $this->hasMany(Attachment::class, 'ref_id', 'shop_id');
}
dd(Shop::find(34)->attachments()->first());
dd(Shop::with('attachments')->get());
首先使用 dd returns 我与 34 关联的附件,但是 with 查询不起作用并且 returns 随便逛逛
我猜你必须在你的商店模型中定义一对多关系(因为一个商店可以有多个附件)。
也许是这样的:
// In Shop model
public function attachments()
{
return $this->hasMany(Attachment::class, 'ref_id', 'shop_id');
}
然后就可以这样使用了(不一定要用find,想用where也可以):
$attachment = Shop::find(1)->attachments()->first();
https://laravel.com/docs/9.x/eloquent-relationships#one-to-many
首先在Shop
模型中添加附件关系功能
class Shop
{
...
public function attachments()
{
return $this->hasMany(Attachment::class, 'ref_id', 'shop_id');
}
}
然后您可以使用 Shop
对象上的 ->attachments()
访问商店附件。
通过分页获取所有内容的示例:(eager loading)
$shops = Shop::with('attachments')->paginate(10);
# access to first attachment of first shop
$shops->first()->attachments->first()->name
注意: 当你想访问所有商店附件时最好使用预先加载来防止 N+1 查询问题
我有两个表 :: shops
和 attachments
。商店有商店的所有详细信息和附件,以及商店的所有图片,ref_id
作为 FK。
现在对于移动应用程序,我必须列出带有商店标题和一张图片的商店。我可以使用 leftjoin 实现它,如下所示。
Shop::select('shops.name as shop_name','attachments.name as picture')
->leftjoin('attachments','attachments.ref_id','=','shops.shop_id')
->paginate(10);
这个returns只是店名和图片, 我想使用我不确定该怎么做的关系来获得相同的结果。有人可以就此给我建议吗
编辑
店铺模型
public function attachments(){
return $this->hasMany(Attachment::class, 'ref_id', 'shop_id');
}
dd(Shop::find(34)->attachments()->first());
dd(Shop::with('attachments')->get());
首先使用 dd returns 我与 34 关联的附件,但是 with 查询不起作用并且 returns 随便逛逛
我猜你必须在你的商店模型中定义一对多关系(因为一个商店可以有多个附件)。
也许是这样的:
// In Shop model
public function attachments()
{
return $this->hasMany(Attachment::class, 'ref_id', 'shop_id');
}
然后就可以这样使用了(不一定要用find,想用where也可以):
$attachment = Shop::find(1)->attachments()->first();
https://laravel.com/docs/9.x/eloquent-relationships#one-to-many
首先在Shop
模型中添加附件关系功能
class Shop
{
...
public function attachments()
{
return $this->hasMany(Attachment::class, 'ref_id', 'shop_id');
}
}
然后您可以使用 Shop
对象上的 ->attachments()
访问商店附件。
通过分页获取所有内容的示例:(eager loading)
$shops = Shop::with('attachments')->paginate(10);
# access to first attachment of first shop
$shops->first()->attachments->first()->name
注意: 当你想访问所有商店附件时最好使用预先加载来防止 N+1 查询问题