laravel 5.4未定义的属性:stdClass :: $ id

时间:2017-07-09 04:23:04

标签: php laravel-5.4

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

$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并按songs.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($艺术家)我可以看到所有收藏品返回但是当我发送到视图时,我收到此错误消息。

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

但是当我(艺术家)这是输出时。

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

非常感谢您的帮助。

3 个答案:

答案 0 :(得分:0)

尝试返回视图,如下所示:

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

修改 要传递多个变量,有许多解决方案。像:

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

答案 1 :(得分: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();

答案 2 :(得分:0)

问题似乎在你的查询中,你选择了两次,第二个选择语句覆盖了第一个,这就是为什么你只得到“WEEKHITS” 结合两个select语句。