2014-11-04 113 views
0

我有三个表:Laravel雄辩属于多个通过

  • 用户(ID,姓名)
  • 任务(ID,标题)
  • task_user(ID,TASK_ID,USER_ID,user_post_id)
  • user_posts(id,title)

我想要做的是取得与该项目相关的所有用户。

在任务模式,我有:

class Task extends \Eloquent { 


    protected $guarded = []; 


    public function users() 
    { 
     return $this->belongsToMany('\User')->withPivot('user_post_id', 'hours'); 
    } 


} 

,并且是相当不错的。我得到这个结果:

[0] => Array 
(
    [id] => 9 
    [created_at] => 1996-08-04 08:35:59 
    [updated_at] => 1991-07-27 16:36:47 
    [username] => xcremin 
    [email] => [email protected] 
    [remember_token] => $2y$10$WmtDoCCIA25Z/CF28KqlwOngR5vHvghD3cu0bbtPGftUV/ez2WBGe 
    [pivot] => Array 
     (
      [task_id] => 1 
      [user_id] => 9 
      [user_post_id] => 10 
     ) 

) 

在这里你可以看到数据库user_post_id字段。问题是 - 我如何获取该字段的标题(user_post_id = 10)?

+0

你会必须在'user_posts'的用户中建立关系 – Jerodev 2014-11-04 20:03:23

回答

0

你必须在你的TaskUser类

public function userPost() 
    { 
     return $this->belongsTo('UserPost'); 
    } 

后你马上就能在你看来做这样的事情来获得名称添加关系

@foreach($task->users as $user) 
     {{ $user->pivot->userPost->title }} 
    @foreach 
-1
$user_posts = DB::table("user_post") 
       ->whereIn("user_post_id", array($user_post_id)) 
       ->get();