所以我正在学习Laravel 5,并且有一个关于多对多关系的问题。我正在构建一个推特克隆,并希望允许创建推文和转发。我的数据库设置是(如透视表的laravel文档中所述)
users
- id
- name
tweets
- id
- content
tweet_user
- tweet_id
- user_id
我的User
和Tweet
模型具有适当的belongsToMany
调用来连接这些关系。
来自User.php
public function tweets() {
return $this->belongsToMany('App'Tweet');
}
来自Tweet.php
public function users() {
return $this->belongsToMany('App'User');
}
最后,我的tweet_user数据透视表看起来像:
|--------------------|
| tweet_id | user_id |
|--------------------|
| 1 | 1 |
|--------------------|
| 1 | 2 |
|--------------------|
因此,为了显示推文,我做了:
return view('tweets.index')->withTweets(App'Tweet::all())
并将其传递给我的观点。在这一点上一切都很好,我的视图将显示2条推文(如上面的tweet_user透视表所示)。然后我的视图有:
@foreach($tweets as $tweet)
{{ $tweet->user->name }} <-issue is here
{{ $tweet->content }} <- all good here
@endforeach
因此,由于我有这种多对多的设置,$tweet->user
是拥有这条推文的所有用户的数组/集合。如何访问上面循环中当前推文的实际用户模型(第一个循环为IE用户id 1,第二个循环为用户id 2)?我肯定我错过了一些简单的东西,但我是否需要在推特/用户模型上使用其他访问器?我最初将此设置作为hasMany
/belongsTo
关系,因此上面的循环运行良好。谢谢你的帮助!
为了便于阅读,如果是多对多,我会将$this->user
重命名为$this->users
。
然后类似于:
@foreach($tweets as $tweet)
@foreach($tweet->users as $user)
{{ $user->name }}
@endforeach
{{ $tweet->content }} <- all good here
@endforeach
这是因为你已经建立了一种多对多的关系。不过,您可能希望按顺序排序或以某种方式标记原始用户。