如何根据Laravel中另一个表的条件查询表?

如何根据Laravel中另一个表的条件查询表?,laravel,eloquent,Laravel,Eloquent,在我的laravel项目中,我有一份清单和一份药物表,其格式如下: 库存表 id | medicine_id | expiry_date -------|-----------------|------------- 1 | 1 | 13-11-2021 2 | 2 | 01-01-2020 3 | 2 | 23-05-2024 id | n

在我的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
药物表

  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');
    }
}
医学模式

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>";
        }

    }
公共功能索引()
{
$medicines=Inventory::where('medicine_id'->类别,“注射器”)->get();
foreach($medicines as$medicine){
echo$medicine->medicine->name.“$medicine->expiration\u date;
回声“
”; } }

现在,是否仍然可以根据它们所属的类别获取所有库存项目?在这种情况下,在“注射器”类别中?

您的语法有点错误,为了装载每个库存的药物,您需要使用
where
函数
where('column',value)
因此,将其更改为:

$medicines = Inventory::with([
  'medicine' => function($query) {
       $query->where('category', "Syringe");
  }    
])->get();
或者更好的办法是:

$medicines = Medicine::with('inventory')->where('category', 'Syringe')->get();

您的语法有点错误,为了为每个库存装载药物,您需要使用
where
函数
where('column',value)
因此,将其更改为:

$medicines = Inventory::with([
  'medicine' => function($query) {
       $query->where('category', "Syringe");
  }    
])->get();
或者更好的办法是:

$medicines = Medicine::with('inventory')->where('category', 'Syringe')->get();