2017-06-30 14 views
0

一个一对多的关系,我有4种型号:postsuserscategoriesuserCategories如何查询只有一个外排在Laravel 5

posts - users有一对多的关系(一个帖子属于一个用户)。

posts - categories有一对多的关系(一个帖子属于一个类别)。

users - userCategories有一对多的关系(一个用户有很多userCategories)。 userCategory具有一个rank字段,该字段保存特定类别的用户表现。

查询一些职位与此:

$posts = Post::with(array('user.userCategories') 
       ) 
      ->where('category_id', '=', $category_id) 
      ->get(); 

评估帖子后,我试图让用户对这篇文章的类别userCategory rank

$rank_of_the_post_owners = array(); 
foreach($posts as $post) 
    foreach($post->user->userCatergories as $userCategory) 
     if($userCategory->id == $post->category_id) { 
      $rank_of_the_post_owners [$post->id] = $userCategory->rank; 
      break; 
     } 
    } 
} 

为了摆脱码以上,我想只查询相关userCategory(该职位的类别)。所以,我想访问排名信息,如user.userCategory-> rank而不是循环。

我该怎么做?

回答

1

当使用with()您可以通过使用一个封闭的价值约束的关系,因为你已经有$category_id,你可以这样做:

$posts = Post::with(['user.userCategories' => function ($query) use ($category_id) { 
     $query->where('userCategories.id', $category_id); 
    }]) 
    ->where('category_id', '=', $category_id) 
    ->get(); 

然后,如果你想,你可以添加一个访问到得到行列的帖子:

public function getRankAttribute() 
{ 
    return $this->user->userCategories->sum('rank'); 
} 

所以访问等级你只需要:

$posts->first()->rank; 

https://laravel.com/docs/5.4/eloquent-mutators#accessors-and-mutators

希望这有助于!