【问题标题】:Different relation by condition因条件而异的关系
【发布时间】:2018-03-10 23:45:43
【问题描述】:

我有 followers 表,其中有:

id, user_id, follower_id, type

type = 关注类型,如果关注 user = 0,page = 1,group = 1

我也使用 user_id 来放置 page_idgroup_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”关系。不知道关系对不对……

有人可以帮助我吗?

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    嗯,在我看来,你应该修改你的迁移。

    而不是让你的桌子:

    id, user_id, follower_id, type
    

    我会这样做的:

    id, user_id, page_id, group_id, follower_id, type
    

    不要在数据库中做类似的奇怪事情,只需在迁移表中添加 2 个字段和/或关系即可。将其设置为 unsigned() AND nullable(),这样您就可以快速知道您的每个页面或组是否存在关系,并且您不必制作奇怪的东西来检查它:D

    【讨论】:

      猜你喜欢
      • 2019-04-13
      • 1970-01-01
      • 1970-01-01
      • 2019-12-25
      • 2017-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多