选择具有laravel雄辩关系的数据

时间:2017-01-01 15:14:01

标签: php mysql eloquent laravel-5.3

我试图了解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在大多数流行表中。

1 个答案:

答案 0 :(得分:1)

如果eloquent get()将返回一个数组,则无法在数组上调用关系方法。

您可以使用first()替换get()或

更改

 $mp = $malayalamSongs;
 dd($mp->song_detail);

   $mp = $malayalamSongs;
   foreach($mp as $v)
   {
     dd($v->song_detail);
   }
相关问题