【发布时间】:2015-12-14 14:25:17
【问题描述】:
我有模型多对多关系之类的。我想通过数据透视表 CategoryNews 关联 State 和 Category。
类别模型
class Category extends Model
{
public function news() {
return $this->belongsToMany('App\News');
}
}
新闻模型
class News extends Model
{
public function categories()
{
return $this->belongsToMany('App\Category');
}
public function state()
{
return $this->belongsTo('App\State');
}
}
和状态模型
class State extends Model
{
public function news() {
return $this->hasMany('App\News');
}
}
我想选择与 cat_type=2 的状态相关的新闻(来自类别表) 我试过了
$slide_news = State::whereHas('news.categories',function($query){ $query->where('categories.cat_type',2);})
->with(array('news'=>function($query){
$query->orderBy('created_at', 'desc');}
))->where('id',$id)->first();
但是 cat_type 过滤器不起作用。我也尝试过 hasManyThrough 但我不知道如何使用数据透视表来实现它 请帮忙
【问题讨论】:
标签: laravel-5 many-to-many pivot-table has-many-through