php – Laravel 5.1在同一模型上有多对多关系
发布时间:2020-12-14 19:42:39 所属栏目:大数据 来源:网络整理
导读:我看到在Laravel的ORM中纠结了以下内容: Scenerio:所有用户都有一个监视列表,监视列表包含其他用户. 我似乎无法让关系正常工作,因为它们是周期性的,到目前为止,我有以下内容: class UserWatchlist extends Model{ protected $table = 'UserWatchlist'; pu
我看到在Laravel的ORM中纠结了以下内容:
Scenerio:所有用户都有一个监视列表,监视列表包含其他用户. 我似乎无法让关系正常工作,因为它们是周期性的,到目前为止,我有以下内容: class UserWatchlist extends Model { protected $table = 'UserWatchlist'; public function Owner() { return $this->belongsTo('AppUser'); } public function WatchedUsers() { return $this->hasMany('AppUser'); } } 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('AppUserWatchlist'); } public function WatchedBy() { return $this->belongsToMany('AppUserWatchlist'); } } 它并没有超越我期待的正确的形成.我错过了什么基本的东西? 解决方法
由于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','watched_id','user_id' ); } } 检查here以获取有关多对多关系的更多信息 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |