douruduan8812 2017-05-24 14:51
浏览 144
已采纳

Laravel - 按关系表排序

I have 2 tables issues and magazines and they have a relationship set up like this:

Magazines model:

 public function issues()
 {
     return $this->hasMany('App\Issue');
 }

Issues model:

public function magazine()
{
    return $this->belongsTo('App\Magazine');
}

In the magazines table I have a column order where the order number of the magazine is. I need to display the latest issue of each magazine, ordered by the magazine order. Now I am displaying latest issue of each magazine ordered by the date of issues.

        $issues = Issue::orderBy('date', 'desc')->get()->groupBy('magazine_id');

        foreach ($issues->first() as $issue)
        {
            $images[] = $issue->image;
        }

And that works fine. But with the new query:

         $magazines = Magazine::with('issues')->orderBy('order')->get();


        foreach ($magazines as $magazine)
        {
            $issues = $magazine->issues()->first();
            $images[] = $magazine->issues()->first()->image;
        }

I get the error:

Trying to get property of non-object

  • 写回答

1条回答 默认 最新

  • dougongyou7364 2017-05-24 15:45
    关注

    Just check if issue is_null, if not, add the image to $images:

        foreach ($magazines as $magazine)
        {
            $issue = $magazine->issues()->first();
            if (!is_null($issue) {
                $images[] = $issue->image;
            }
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法