2015-09-05 147 views
0

我想创建一个简单的活动饲料,用户可以看到他的朋友的更新。Laravel雄辩活动饲料

我处理三个表。 user_status,友谊和用户。

用户表

user_id 
name 
email 
..(a regular users table, nothing special) 

友谊表

friendship_id 
friend_one (Foreign key from users table) 
friend_two (Foreign key from users table) 

user_status表

status_id 
user_id (foreign key from users table) 
status 
date 

MODELS

用户模型

public function friends() { 
    return $this->belongsToMany('App\Models\User', 'friendship', 'friend_one', 'friend_two'); 
} 

public function status() { 
     return $this->hasMany('\App\Models\UserStatus','status_id'); 
    } 

UserStatus模型

public function usersStatus() { 
    return $this->belongsTo('\App\Models\User','user_id'); 
} 

FeedController.php

class FeedController extends Controller 
{ 
    public function index() { 

     $friends = Auth::user()->friends; 


     return view('frontend.feed.index') 
      ->with('friends',$friends); 
    } 

} 

使用下面的查询,我可以得到一个用户的好友。我也可以轻松获得特定用户的状态更新,但我不知道如何仅列出特定用户的状态。

@foreach($friends as $friend) 
    {{$friend->email}} 
@endforeach 

下面的一个不起作用。

查看

@foreach($friends as $friend) 
    @foreach($friend->status as $status) 
     {{$status->status}} 
    @endforeach 
@endforeach 


Invalid argument supplied for foreach() (View: /Applications/MAMP/htdocs/master/resources/views/frontend/feed/index.blade.php) 

回答

1

我认为这个问题是您的foreign_key参考

public function status() { 
     return $this->hasMany('\App\Models\UserStatus','status_id'); 
} 

更改为:

public function status() { 
     return $this->hasMany('\App\Models\UserStatus', 'user_id', 'user_id'); 
} 

,它应该工作。

+0

它不起作用,我得到相同的错误。请问为什么在关系中有两个user_id? – salep

+1

既然你不使用默认的id,你将不得不重写你的local_key和foreign_key引用格式 $这个 - >的hasMany(“应用程序\型号\ UserStatus,‘foreign_key’,‘local_key’)。现在因为你的foreign_key和local_key都是user_id。 http://laravel.com/docs/5.1/eloquent-relationships#one-to-many –

+0

还有,为什么你在你的UserStatus模式usersStatus()方法。它应该是user()。 –