2017-07-09 160 views
0

我有两个模型艺术家和歌曲有一对多的关系,艺术家可以有多首歌曲。歌曲属于一位艺术家。

$artists = DB::table('artists')->join('songs', 'artists.id', '=', 'songs.artist_id')->select('artists.*, songs.id, songs.title, songs.artist_id, songs.week_hits, songs.created_at') 
      ->SELECT(DB::raw('sum(songs.week_hits) as WEEKHITS'))->groupBy('songs.artist_id')->orderBy('WEEKHITS', 'DESC')->take(7)->get(); 
return return view('front.home', compact('videos', 'songs', 'artists', 'played', 'uploads', 'albums')); 

这是我的控制器代码。因为你可以看到我添加了所有的艺术家歌曲week_hits并按歌曲分组.artist_id

这是我的观点。

@foreach($artists as $artist) 
      <div class="artist-grid"> 
       <div class="art-img"> 
        <a href="{{route('artist',['id' => $artist->id, 'slug' => $artist->slug])}}"> 
         <img src="image/small/{{$artist->image}}"> 
        </a> 
       </div> 
       <div class="name"> 
        <h3>{{$artist->name}}</h3> 
       </div> 
      </div> 
      @endforeach 

但是当我DD($艺术家),我可以看到所有收集回来,但是当我发送到视图IAM收到此错误消息。

(2/2) ErrorException 
Undefined property: stdClass::$id (View: C:\xampp\htdocs\laravel\resources\views\front\home.blade.php) 

但是当我dd($ artists)这是输出。

Collection {#293 ▼ 
    #items: array:4 [▼ 
    0 => {#307 ▼ 
     +"WEEKHITS": "39" 
    } 
    1 => {#292 ▼ 
     +"WEEKHITS": "9" 
    } 
    2 => {#278 ▼ 
     +"WEEKHITS": "4" 
    } 
    3 => {#308 ▼ 
     +"WEEKHITS": "1" 
    } 
    ] 
} 

请真的感谢您的帮助。

+0

你可以dd()$艺术家收藏价值并向我们展示单一入境的结果吗? –

+0

这是当我dd($艺术家)变量。集合{#293▼ #items:数组:4 [▼ 0 => {#307▼ + “WEEKHITS”: “39” } 1 => {#292▼ + “WEEKHITS”: “9” } 2 => {#278▼ + “WEEKHITS”: “4” } 3 => {#308▼ + “WEEKHITS”: “1” } ] } –

回答

0

尝试返回查看如下:

return view('front.home')->with($artists, compact('artists')); 

编辑 要传递多个变量有许多解决方案。像:

return view('front.home')->with(compact('videos', 'songs', 'artists', 'played', 'uploads', 'albums')); 
+0

抱歉,我没有提以上,我不仅发送$艺术家变量来查看,还有另一种观点,返回视图('front.home',compact('视频','歌曲','艺术家','播放','上传','相册)); –

+0

您可以使用多个'with'发送多个变量。看到我更新的鼻炎@MahamoudMahamed –

+0

是的,我的意思是仍然是相同的错误,没有变化 –

0

请看看您的查询,你必须选择查询中的SELECT()选项也id。

$artists = DB::table('artists')->join('songs', 'artists.id', '=', 'songs.artist_id')->select('artists.*, songs.id, songs.title, songs.artist_id, songs.week_hits, songs.created_at') 
      ->SELECT(DB::raw('sum(songs.week_hits) as WEEKHITS','artists.id as id'))->groupBy('songs.artist_id')->orderBy('WEEKHITS', 'DESC')->take(7)->get(); 

OR

$artists = DB::table('artists')->join('songs', 'artists.id', '=', 'songs.artist_id')->select('artists.*, songs.id, songs.title, songs.artist_id, songs.week_hits, songs.created_at') 
       ->SELECT(DB::raw('sum(songs.week_hits) as WEEKHITS','artists.*'))->groupBy('songs.artist_id')->orderBy('WEEKHITS', 'DESC')->take(7)->get(); 
+0

仍然没有改变,但我做到了。我认为问题在于这一部分。

+0

请在dd()内的foreach()然后你可以看到$艺术家对象的实际情况。 –

相关问题