2017-01-01 93 views
1

我想了解laravel雄辩的关系,所以我创建了两个表。在laravel迁移定义的表的结构是 为mostpopular表用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模型定义的函数对与2表

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获得歌曲的细节是mostpopular表。

+1

您song_detail模型需要需要通过belongsTo –

+0

确定我加入公共职能songsdetail( ) { \t return $ this-> belongTo('App \ Mostpoular'); } –

+0

但我得到相同的错误 –

回答

1

eloquent get()会返回一个数组,你不能调用数组上的关系方法。

,你可以先用()取代的get()或

变化

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

$mp = $malayalamSongs; 
    foreach($mp as $v) 
    { 
    dd($v->song_detail); 
    } 
+0

错误消失了,但页面空白没有显示 –

+0

对不起空白页是因为我删除了get()所以我把它放回去,但我得到null insted歌曲的详细信息 –

+1

请确保查询有结果。如果不是的话,结果为空 –