我似乎在Laravel的ORM中遇到了以下问题:
场景:所有用户都有一个观看列表,该列表包含其他用户。
由于关系是循环的,因此我似乎无法使关系正常工作,目前我有以下内容:
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
模型:您永远不必为中间表编写模型。 - Moppo