【发布时间】:2018-03-10 23:45:43
【问题描述】:
我有 followers 表,其中有:
id, user_id, follower_id, type
type = 关注类型,如果关注 user = 0,page = 1,group = 1
我也使用 user_id 来放置 page_id 和 group_id。
现在问题来了,如果type不同,我想建立不同的关系...如果type = 0,将与users表和share表相关,如果type = 1,将与pages表相关...
我是这样尝试的:
型号:
public function page_links()
{
return $this->hasMany(Link::class, 'page_id', 'user_id')->Select('links.id', 'links.title', 'links.photo', 'links.country', 'links.friendly_url', 'links.clicks', 'links.description', 'links.suggestions', 'links.count_comments', 'links.url', 'links.shares', 'links.page_id', 'links.tag_id', 'links.created_at')->where('sponsored', 0)->where('scheduled', 0)>where('status', 1)->take(3)->orderBy('id','desc');
}
public function user_links()
{
return $this->hasMany(Share::class, 'user_id', 'user_id')->Select('id', 'link_id', 'user_id', 'shared_in', 'content', 'created_at')->take(3)->orderBy('id', 'desc')->where('type', '=', 0);
}
public function scopeProfile($query) {
return $query
->when($this->type == 0, function($q){
return $q->with('user_links');
})
->when($this->type == 1, function($q){
return $q->with('page_links');
})
->when($this->type == 2, function($q){
return $q->with('group_links');
});
}
控制器:
$feed = Feed::Profile()->where('follower_id', auth()->user()->id)
->take(10)
->get();
但是 ALL,即使是类型 1 也会返回“user_links”关系。不知道关系对不对……
有人可以帮助我吗?
【问题讨论】: