使用关系 eloquent laravel 搜索时如何获取数据
How can I get data when I search using relationship eloquent laravel
如何在 eloquent laravel
中获取价值关系
这是我的模特食物
class food extends Model
{
protected $table = 'food';
protected $fillable = [
'name'
];
public function foodType()
{
return $this->belongsTo(Food_type::class, 'food_type_id');
}
}
这是我的 food_type 模型
class food_type extends Model
{
protected $table = 'food_type';
protected $fillable = [
'name', 'description'
];
public function getFood()
{
return $this->hasMany(Food::class);
}
}
我想在food_typetable中得到food_type.name,这样怎么查询
$search = $request->search
$food = Food::with(['foodType'])
->where('name', 'like', '%'.$search.'%')
->orWhere('foodType.name', 'like', '%'.$search.'%')->get();
当您使用预先加载时,连接不包含关系。查看 documentation,因为它涵盖了如何使用 whereHas 和其他与关系相关的方法。
$food = Food::with(['foodType'])
->where('name', 'like', '%'.$search.'%')
->orWhereHas('foodType' function($q) {
$q->where('name', 'like', '%'.$search.'%');
})
->get();
如何在 eloquent laravel
中获取价值关系这是我的模特食物
class food extends Model
{
protected $table = 'food';
protected $fillable = [
'name'
];
public function foodType()
{
return $this->belongsTo(Food_type::class, 'food_type_id');
}
}
这是我的 food_type 模型
class food_type extends Model
{
protected $table = 'food_type';
protected $fillable = [
'name', 'description'
];
public function getFood()
{
return $this->hasMany(Food::class);
}
}
我想在food_typetable中得到food_type.name,这样怎么查询
$search = $request->search
$food = Food::with(['foodType'])
->where('name', 'like', '%'.$search.'%')
->orWhere('foodType.name', 'like', '%'.$search.'%')->get();
当您使用预先加载时,连接不包含关系。查看 documentation,因为它涵盖了如何使用 whereHas 和其他与关系相关的方法。
$food = Food::with(['foodType'])
->where('name', 'like', '%'.$search.'%')
->orWhereHas('foodType' function($q) {
$q->where('name', 'like', '%'.$search.'%');
})
->get();