doupu1949 2015-01-12 15:30
浏览 89

Laravel加入Auth表

I'm using the default Authentication system that Laravel provides. However, I want to join two tables (perform two inner joins) on my Auth table (users). So far, I have created two relationships between two models and this works fine and gets me the data I want, however it performs two extra queries when I think in hindsight doing two joins on the table would be much more efficient.

What I don't know how to do is to perform the Joins on the User Model so that I'm not having to create a new query (but rather use the one that is created by calling Auth::user()).

My tables:

    Users: id username iconid avatarid
    Icons: id image
    Avatars: id image

So what I'd like to do is:

    SELECT icons.image as icon_image, avatars.image as avatar_image FROM users
    LEFT OUTER JOIN icons ON icons.id = users.iconid
    LEFT OUTER JOIN avatars ON avatars.id = users.avatarid

Is this possible? Do I just need to overwrite a method in my User model in order for Auth::user() to run the above query?

Thank you to anyone who replies!

  • 写回答

1条回答 默认 最新

  • drw85135 2015-01-12 15:35
    关注

    Put this in your user model:

    public function icon()
    {
        return $this->hasOne('Icon');
    }
    public function avatar()
    {
        return $this->hasOne('Avatar');
    }
    

    Then get the user like this:

    $user = User::with(['icon', 'avatar'])->find(1);
    

    Then you can access the icon and avatar like this:

    $user->icon
    
    $user->avatar
    

    To do this with joins you can do this:

    $user_id = 1;
    DB::table('users')
    ->join('icons', 'icons.id', '=', 'users.icon_id')
    ->join('avatars', 'avatars.id', '=', 'users.avatar_id')
    ->select('users.name', 'icons.path', 'avatars.path')
    ->where('users.id', $user_id)
    ->first();
    
    评论

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据