【问题标题】:Excluding pivot rows in Eloquent ORM query在 Eloquent ORM 查询中排除数据透视行
【发布时间】:2015-10-16 16:43:44
【问题描述】:

(laravel 4.2)

涉及四个表;用户、帖子、标志和 post_flags。

我想检索某个用户拥有的每个帖子,并检索为该帖子设置的标志,但只检索相关用户设置的标志。

例如:帖子可以有标志:1、2、2、3,其中标志 2 设置了两次。用户 A 一次,用户 B 一次。我不想看到用户 B 设置的标志。

我的控制器中的 Eloquent 查询:

$posts = Post::whereHas('companies', function($q) use($company_id) {
        $q->where('id', '=', $company_id);
    })->with('flags')->get();

我的 Post 模型中的关系:

public function flags() {
    return $this->belongsToMany('PostFlag', 'post_postflags', 'post_id', 'flag_id')
    ->withTimestamps()->withPivot('owner');
}

我如何使用 Eloquent ORM 实现这一目标?

更新

感谢 andrewtweber,我的最后一个问题:

最终查询

$posts = Post::whereHas('users', function($q) use($id) {
            $q->where('id', '=', $id);
         })->get()->load([
            'flags' => function($query) use($id) {
                $query->where('owner', '=', $id)->orWhere('owner', '=', 'SYSTEM');
            }
         ]);

【问题讨论】:

    标签: laravel orm eloquent


    【解决方案1】:

    使用wherePivot

    http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Relations/MorphToMany.html

    $flags = $post->flags()
        ->wherePivot('user_id', '=', $user_id)
        ->get();
    

    或者急切加载

    $posts->load([
        'flags' => function ($query) use($user_id) {
            $query->wherePivot('user_id', '=', $user_id);
        }
    ]);
    

    【讨论】:

      猜你喜欢
      • 2014-12-20
      • 2018-11-11
      • 2015-06-24
      • 2018-12-08
      • 2011-02-06
      • 2015-02-04
      • 2015-09-30
      • 2012-12-31
      相关资源
      最近更新 更多