【问题标题】:How to get result from database based on the user with laravel如何使用 laravel 基于用户从数据库中获取结果
【发布时间】:2021-11-29 18:38:24
【问题描述】:

我开始编写 laravel 代码,一切都很好,直到我想根据用户获得结果,怎么做,我需要做什么?

【问题讨论】:

    标签: php laravel-5 eloquent backend


    【解决方案1】:

    你可以使用 where 子句。

    假设您想获取某个用户的所有博客。

    喜欢:

    Blog::where('user_id', Auth::user()->id)->get();
    
    // Auth::user()->id returns the logged in user's id.
    
    

    或者

    在用户模型中创建关系

    App\Models\User
    
    use App\Models\Blog;
    
     public function blogs()
     {
         return $this->hasMany(User::class, 'user_id', 'id');
     }
    
    

    然后

    Auth::user()->blogs;
    

    【讨论】:

    • 非常感谢,这很简单,但我认为它更难。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-03
    • 2019-04-28
    • 2021-09-23
    • 2018-09-15
    • 1970-01-01
    • 2018-08-17
    相关资源
    最近更新 更多