我试图了解laravel雄辩的关系所以我创建了两个表。在laravel迁移中定义的表的结构是 对于最流行的表
Schema::create('mostpopulars',function(Blueprint $table){
$table->increments('id');
$table->integer('song_id')->unsigned();
$table->index('song_id');
$table->foreign('song_id')->references('id')->on('song_details')->delete('cascade');
});
用于song_detail表
Schema::create('song_details', function (Blueprint $table) {
$table->increments('id');
$table->string('song_title');
$table->string('song_name');
$table->string('song_album');
$table->string('song_singer');
$table->string('song_musicby');
$table->string('song_location');
$table->string('song_album_image');
$table->string('song_language');
$table->string('song_lyrics',3000);
$table->timestamps();
});
然后在Mostpopular模型中定义了关联两个表的函数
public function song_detail()
{
return $this->hasOne('App\Song_detail','id');
}
并且在控制器索引功能中我想做类似这样的事情
$songs = Song_detail::select()->latest()->get();
$malayalamSongs = Mostpopular::select('song_id')->groupBy('song_id')->havingRaw('COUNT(*) > 2')->get();
$mp = $malayalamSongs;
dd($mp->song_detail);
但是收到错误
Undefined property: Illuminate\Database\Eloquent\Collection::$Song_detail
请帮助我找到错误,我想要做的是从song_details表中获取歌曲的详细信息song_id
发生两次以上song_id
在大多数流行表中。
答案 0 :(得分:1)
您可以使用first()替换get()或
更改
$mp = $malayalamSongs;
dd($mp->song_detail);
到
$mp = $malayalamSongs;
foreach($mp as $v)
{
dd($v->song_detail);
}