在我的laravel项目中,我有一份清单和一张医药表,其格式如下:
库存表
id | medicine_id | expiry_date
-------|-----------------|-------------
1 | 1 | 13-11-2021
2 | 2 | 01-01-2020
3 | 2 | 23-05-2024医学表
id | name | category
-------|-----------------|-------------
1 | Hemophine | Syringe
2 | andrenalin | Tablet
3 | aspirin | Capsule这些模型如下:
库存模型
class Inventory extends Model
{
public $incrementing = false;
public function medicine(){
return $this->belongsTo('App\Medicine', 'medicine_id');
}
}医学模型
class Medicine extends Model
{
public $incrementing = false;
public function inventory(){
return $this->hasMany('App\Inventory', 'medicine_id');
}
}为了检索所有特定类别的库存,如注射器,我尝试了急切的加载,但无法找出缺陷。以下是我用注射器分类得到所有库存的方法,但没有奏效。
public function index()
{
$medicines = Inventory::where('medicine_id'->category, "Syringe")->get();
foreach($medicines as $medicine){
echo $medicine->medicine->name ." ".$medicine->expiry_date;
echo "<br>";
}
}现在,是否有得到所有库存项目,根据他们的类别,他们在其中?在这种情况下属于“注射器”类?
发布于 2019-01-03 09:02:02
您的语法有点错误,为了加载您需要使用with和where函数是where('column', value)的每个库存的药物,所以将其更改为:
$medicines = Inventory::with([
'medicine' => function($query) {
$query->where('category', "Syringe");
}
])->get();或者更好的情况是:
$medicines = Medicine::with('inventory')->where('category', 'Syringe')->get();https://stackoverflow.com/questions/54018906
复制相似问题