laravel怎么查找type_id = 1的所有店铺
发布网友
发布时间:2022-04-25 19:10
我来回答
共1个回答
热心网友
时间:2023-10-13 19:22
//1. 分步查询
// 查出所有符合type_id=1的shop_id
$types = Type::query()
->where('type_id', 1)
->get(['shop_id'])
->toArray();
$shop_ids = array_pluck($types, 'shop_id');
// 去shop表用in查询
$shops = Shop::query()
->whereIn('id', $shop_ids)
->get();
//2. relation查询
// 查出所有符合type_id=1的shop_id的同时级联查询相关的shop信息
$types = Type::query()
->where('type_id', 1)
->with(['shop'])
->get()
->toArray();
$shops = array_pluck($types, 'shop');
// relation查询需要先去type的model里添加shop的关联
class Type extends Model
{
protected $table = 'type';
protected $fillable = [
// 略
];
public function shop()
{
return $this->hasMany(Shop::class, 'id', 'shop_id');
}
}