调用Laravel Relationship Query中的未定义函数

时间:2019-01-04 14:57:23

标签: php laravel

由于我将有许多搜索过滤器,因此我将按照以下所示的方式来构建它们。我已经显示了一个过滤器(用于帖子),因为这是引发错误的过滤器。

用户模型

public function posts()
{
    return $this->morphToMany('App\Post', 'postable');
}

用户控制器

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\User;

class UserController extends Controller
{

    public function searchPage(Request $request, User $user)
    {

        $user = $user->newQuery();

        if ($request->has('post'))
            $user->posts()->where('id', $request->input('post'));

        return $user->get();

    }

}

我得到:Call to undefined method Illuminate\Database\Eloquent\Builder::posts(),而我认为应该按照the documentation这样做。

1 个答案:

答案 0 :(得分:2)

newQuery()将返回查询生成器的实例。您不能在此基础上建立关系。

public function searchPage(Request $request, User $user)
{
    // newQuery returns an instance of Query Builder
    // You can't chain relationships on the Query Builder
    $user = $user->newQuery();

    // You want an instance of the User model here. 
    // This is just an example
    $user = \App\User::find($request->id); 

    // If you are already passing in the user model
    // you can just use it as it is. No need to do 

    if ($request->has('post')) {
        $user->posts()->where('id', $request->input('post'));
    }

    return $user->get();
}