[英]Laravel eloquent Relationship Query
My database schema is我的数据库架构是
links:
id status user_id url
1 1 1 something
2 1 1 something
3 1 1 something
links_type:
id link_id links_type
1 1 external
2 1 external
3 1 internal
4 1 external
5 2 internal
6 2 external
7 2 internal
8 2 external
i want to take data of all links which status is 1 and user_id is 1 and count external and internal links and which external count is >2.我想获取状态为 1 且 user_id 为 1 的所有链接的数据,并计算外部和内部链接以及外部计数 > 2。
by using laravel 5.2 eloquent.通过使用 laravel 5.2 eloquent。
result should be like this from data given结果应该是这样从给定的数据
id status user_id url external_links internal_links
1 1 1 something 3 1
Just define this relationship in Link
Model只需在
Link
模型中定义此关系
public function link_type()
{
return $this->hasMany('App\linkType');
}
and use this query并使用此查询
Link::where('status','=','1')->where('user_id','=','1')->has('link_type','>', '2')->with('link_type')->get();
If you already have the right migrations with fk's and Models following code should be working:如果您已经使用 fk 和 Models 进行了正确的迁移,则以下代码应该可以正常工作:
$links = Link::where('status','=','1')->where('user_id','=','1') ->whereHas('links_type',function ($query) { $query->whereNotIn('external_count', [0,1]); })->get();
Probably should add with('links_type') for eager_loading (N+1 problem):可能应该添加 with('links_type') 用于eager_loading(N+1 问题):
$links = Link::with('links_type')->where('status','=','1')->where('user_id','=','1') ->whereHas('links_type',function ($query) { $query->whereNotIn('external_count', [0,1]); })->get();
maybe this could work.也许这可以工作。
before you must create hasMany relation for Link and name as type在您必须为Link和 name 作为类型创建hasMany关系之前
$links = Link::where('status', 1)
->wherer('user_id', 1)
->whereHas('type', function($query) {
$query->where(
$query->where('links_type', 'external')->count(), '>', 2
);
})
->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.