0

私はいくつかの関連モデルを持っています:

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でもフィルタリングする必要があります。(私の計画は、会社に接続している複数のユーザーがすべてのプロジェクトとクライアントを表示できるようにすることです。)

4

1 に答える 1

2

実際には、クエリから何も取得していません。追加する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);
于 2013-05-11T16:18:23.507 に答える