[英]Laravel 5.1 Multiple Many to Many Relationship on the Same Model
我看到在Laravel的ORM中纠结了以下内容:
Scenerio:所有用户都有一个监视列表,监视列表包含其他用户。
我似乎无法让关系正常工作,因为它们是周期性的,到目前为止,我有以下内容:
class UserWatchlist extends Model
{
protected $table = 'UserWatchlist';
public function Owner() {
return $this->belongsTo('App\User');
}
public function WatchedUsers() {
return $this->hasMany('App\User');
}
}
Schema::create('UserWatchlist', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('Users')->onDelete('cascade');
$table->integer('watched_id')->unsigned();
$table->foreign('watched_id')->references('id')->on('Users')->onDelete('cascade');
$table->timestamps();
});
class User extends Model
{
public function Watchlist() {
return $this->hasOne('App\UserWatchlist');
}
public function WatchedBy() {
return $this->belongsToMany('App\UserWatchlist');
}
}
它并没有超越我期待的正确的形成。 我错过了什么基本的东西?
由于UserWatchlist
是一个数据透视表,我认为你面临着多对多的关系,这两个关系的元素是同一个模型( User
)
如果是这种情况,则不应为数据透视表UserWatchlist
构建模型,但您只需通过数据透视表设置用户之间的关系:
class User extends Model
{
//get all the Users this user is watching
public function Watchlist()
{
return $this->belongsToMany('User', 'UserWatchlist', 'user_id', 'watched_id' );
}
//get all the Users this user is watched by
public function WatchedBy()
{
return $this->belongsToMany('User', 'UserWatchlist', 'watched_id', 'user_id' );
}
}
点击此处查看有关多对多关系的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.