Laravel:无法在嵌套的whereHas中访问belongsToMany关系

时间:2017-01-17 06:45:28

标签: laravel laravel-5 laravel-5.1

我在嵌套的where子句中使用whereHas但我无法这样做。以下是我的模特:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function scopePickedUser($query, $pickedTypeID)
    {
        return $query->where(function($query) use ($pickedTypeID)
        {
            $query->whereHas('photos', function($query) use ($pickedTypeID)
            {
                 $query->whereTypeId($pickedTypeID);
            });


            if($condition){
                $query->orWhere('another_column_id',$var);
            }
        });
    }

    public function photos()
    {
        return $this->belongsToMany(Photo::class);
    }
}

如果我打电话,App\Models\User::pickedUser(4)->get()我收到错误BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::photos()'。这是为什么?我做错了什么?

1 个答案:

答案 0 :(得分:0)

请参阅laravel with以获取Eager Loading和Lazy Eager Loading。我想你可以尝试这两种类型

App\Models\User::with('photos')->pickedUser(4)->get()

public function scopePickedUser($query, $pickedTypeID)
    {
        $query->load('photos');
        return $query->where(function($query) use ($pickedTypeID)
        {
            $query->whereHas('photos', function($query) use ($pickedTypeID)
            {
                 $query->whereTypeId($pickedTypeID);
            });


            if($condition){
                $query->orWhere('another_column_id',$var);
            }
        });
    }