doujiang2812 2015-07-10 19:37 采纳率: 0%
浏览 506
已采纳

Laravel访问关系 - 检查模型中是否存在数据

Let's say I have a User and Group model that has a one-to-many relation. User can belong 0 or 1 group. Group can have many users.

When I show a list of users, I also want to display his group's name--if he belongs to one. So I do this:

$user->group()->first()->name

If the user doesn't belong to a group, this will--of course--throw an error.

So I do something like this:

!empty($user->group) ? $user->group()->first()->name : 'No group here'

Now in my actual app there isn't just group. There a lot more relationships that I loop through from within the view. Like, role, account, etc.

So I don't really want to clutter up my view with that. Is there a way to check if a data exists from within the model?

Something like this, perhaps?

class User extends Model
{
    // .. snip

    public function group()
    {
        if (empty($this->group)) {
            return 'Nothing here';
        }

        return $this->hasOne(App\Group::class);
    }
}

Am I going about this the wrong way? Is this already available? I haven't seen anything on the docs or on google that can help me with this (maybe looking for the googling the wrong words?).

So if anyone could point me in the right direction, that'd be great.

  • 写回答

1条回答 默认 最新

  • donglei2022 2015-07-11 06:05
    关注

    You may create an accessor method in your User model for example:

    public function getGroupNameAttribute()
    {
        $this->group ? $this->group->name : 'Oops! Nothing.';
    }
    

    So, in the view, you can use something like this:

    {{ $user->group_name }}
    

    The output will be either a group name or Oops! Nothing..

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵