【问题标题】:Method is not defined on the Query class查询类上没有定义方法
【发布时间】:2013-05-11 15:28:51
【问题描述】:

我有一些相关的模型:

Client
id, name, user_id ++

Projects
id, title, client_id, user_id ++

Users
id, name ++

一个客户属于一个用户,一个客户有很多项目,一个项目属于一个客户和一个用户。

当我尝试以下查询为客户获取项目时,我收到一条错误消息

Method [projects] is not defined on the Query class.

这是什么意思?

我尝试了以下查询:

Client::find(2)->where('user_id', '=', Auth::user()->id)->projects() // Throws error
Client::where('id', '=', 2)->where('user_id', '=', Auth::user()->id)->projects() // Also throwing an error

以下查询完美运行:

Client::find(2)->projects

我的模型很简单,看起来像这样:

<?php

class Client extends Eloquent
{
    public static $timestamps = TRUE;

    public function user()
    {
        return $this->belongs_to('User');
    }

    public function projects()
    {
        return $this->has_many('Project');
    }
}

class Project extends Eloquent
{
    public static $timestamps = TRUE;

    public function client()
    {
        return $this->belongs_to('Client');
    }

    public function user()
    {
        return $this->belongs_to('User');
    }
}

class User extends Eloquent
{
    public static $timestamps = TRUE;

    public function clients()
    {
        return $this->has_many('Client');
    }

    public function projects()
    {
        return $this->has_many('Project');
    }
}

为什么当我使用 where 子句时它不起作用?它在我不使用 where 子句时有效,但我还需要在 user_id 上过滤项目和客户。 (我的计划是允许连接到公司的多个用户查看他们的所有项目和客户。)

【问题讨论】:

  • 也许是因为方法 'where' 返回了类 Query 的一些新实例,而不是 $this ?

标签: php mysql laravel eloquent database-relations


【解决方案1】:

您实际上并没有从查询中检索任何内容,只需添加 first() 或添加 get() 然后循环并调用您的 projects()

应该像这样工作:

Client::where('id', '=', 2)->where('user_id', '=', Auth::user()->id)->first()->projects()

根据您的评论,它应该也适用于单行:

Client::find(2)->projects()->where('user_id', '=', Auth::user()->id);

【讨论】:

  • 我从 Laravel 论坛得到了另一个答案:Client::find(2)-&gt;projects()-&gt;where('user_id', '=', Auth::user()-&gt;id) 哪个最有效?
猜你喜欢
  • 2020-04-20
  • 2020-11-23
  • 2021-10-21
  • 2017-08-19
  • 2020-12-24
  • 1970-01-01
  • 2021-09-02
  • 2021-08-02
  • 1970-01-01
相关资源
最近更新 更多