【问题标题】:Laravel eloquent how to get relationships relationship?Laravel 雄辩的关系如何获取关系?
【发布时间】:2020-12-02 04:56:42
【问题描述】:

我有用户表、工作表和 JobStatus 表。我使用关系获得用户工作

return User::find($dto->getUserId())
            ->jobs()

这会将所有用户作业作为集合返回,而不是作为用户模型内部的关系。 现在我需要获取工作状态,但是当我尝试这个时

User::find($dto->getUserId())
            ->jobs()
            ->statuses()
            

我收到错误 Call to undefined method。我需要将状态作为集合获取,以便在从 db 获取它们时使用 where、sort by 等。有什么办法吗?

我需要做这样的事情,但有状态

return User::find($dto->getUserId())
            ->jobs()
            ->has('status')
            ->where('role','responsible')
            ->where('jobs.created_at','>=',Carbon::now()->subDays($dto->getPeriod())->toDateString())
            ->get();

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    要通过过滤状态关系来检索作业,您可以这样做:

    $user->jobs()->whereHas('statuses', function ($query) {
        // Perform filter on the query for jobs->statuses
    })->get();
    

    更多关于查询关系存在的信息:https://laravel.com/docs/7.x/eloquent-relationships#querying-relationship-existence


    如果你想检索状态实例,你可以这样做:

    $statuses = JobStatus::where('created_at', '>=', now())
        ->whereHas('jobs', function ($query) use ($user) {
            $query->whereUserId($user->id);
        })
        ->get();
    

    【讨论】:

    • 我不会遍历它们。我需要像工作一样过滤它们。我在问题中添加了示例
    • @randomdude 我明白了,我已经更新了我的答案。这取决于您是想通过过滤状态来检索作业,还是检索状态本身。
    • 我需要自己检索状态,最好没有用户和作业。谢谢你的好回答
    • 没问题!如果您不想使用职位或用户进行过滤,您可以简单地执行JobStatus::where(...)->get();
    【解决方案2】:

    首先使用模型中与作业的关系定义您的 statuses() 函数

    喜欢多对多或一对多的关系

    public function statuses(){
        return $this->belongsToMany('App\Job')->withTimestamps();
    }
    

    【讨论】:

      【解决方案3】:

      只需使用不带括号的作业来获取模型本身:

      User::find($dto->getUserId())
                  ->jobs
                  ->statuses;
      

      【讨论】:

      • 如果我这样做,我会收到错误Property [statuses] does not exist on this collection instance
      猜你喜欢
      • 1970-01-01
      • 2019-07-16
      • 2015-03-14
      • 2018-11-28
      • 2015-01-11
      • 2021-06-03
      • 2020-03-26
      • 1970-01-01
      相关资源
      最近更新 更多