所以,我一直在努力使这个模式起作用(顺便说一下,我是 laravel 的新手......)我有一个“照片”表和一个音频“曲目”表,我希望能够做这样的事情:
轨道模型:
// Get the photo associated with this track.
public function cover_art() {
return $this->hasOne('App\Photo');
}
照片模特:
// Get all the tracks associated with this photo.
public function tracks() {
return $this->belongsToMany('App\Track');
}
表示这种关系的最佳解决方案是什么(一个音轨只能有一张照片,而一张照片可以属于多个音轨)?
好吧,最后我设置了所有内容并得到了预期的错误:
照片表:
Schema::create('photos', function (Blueprint $table) {
$table->increments('id');
$table->string('path');
$table->string('filename');
$table->string('original_filename');
$table->boolean('is_cover')->default(false);
$table->string('title');
$table->string('slug')->unique();
$table->string('caption')->nullable();
$table->timestamps();
});
曲目表:
Schema::create('tracks', function (Blueprint $table) {
$table->increments('id');
$table->integer('photo_id')->unsigned()->nullable();
$table->string('path');
$table->string('filename');
$table->string('original_filename');
$table->string('title');
$table->string('slug')->unique();
$table->string('caption')->nullable();
$table->timestamps();
$table->foreign('photo_id')->references('id')->on('photos')->onDelete('set null');
});
所以现在,例如,当我在我的视图或控制器中调用适当的方法时,我得到这些错误:
@foreach($tracks as $track)
{{ $track->cover_art }}
@endforeach
SQLSTATE [42S22]:找不到列:1054 'where 子句'中的未知列'photos.track_id'(SQL:从
photos
中选择*,其中photos
.track_id
= 1和photos
.track_id
不是空限制 1)
@foreach($photos as $photo)
{{ $photo->tracks }}
@endforeach
SQLSTATE[42S02]: 未找到基表或视图:1146 表 'iagomarta.photo_track' 不存在(SQL:选择
tracks
作为 photo_track
从 photo_id
内部加入 pivot_photo_id
在 photo_track
.track_id
= pivot_track_id
.tracks
其中 photo_track
.tracks
= 1)有什么建议吗?
也许只是打错了如下图:
create_table_tracks_migration :
id
通常最好的做法是以这种方式设置外键引用,因为我自己也遇到过一些问题而没有这样做。
看起来奇怪的是那个错误:
photo_track
无论如何,你的照片表上都不应该有 track_id 列。
除此之外,您可以尝试设置 belongsTo(App\Photo) 关系而不是 hasOne。它会起作用,因为一个轨道只能有一张照片。此外,您不需要数据透视表,因为它是一对多关系,而不是多对多关系。
track_id
可以这样想——“封面艺术”/“照片”代替专辑,所以“专辑”(照片)有很多曲目,所有曲目都属于一张专辑。