我在嵌套的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()'
。这是为什么?我做错了什么?
答案 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);
}
});
}