【问题标题】:get data from multiple relations in laravel eloquent从 laravel eloquent 中的多个关系中获取数据
【发布时间】:2017-03-29 02:31:46
【问题描述】:

我有以下表格 pharmacies,categories,medicines 我正在使用 laravel

关系是这样的

药店有很多药品,药品属于一类

medicines 表有 pharmacy_idcategory_id 列 + 其他列

我想按 id 显示一个药房,它应该返回一个带有类别的药房对象,每个类别都有这个药房中的药品对象。如果没有任何类别的药品,则不应退货。

我认为这是一个模型关系问题

任何想法都可能有用

类别模型

class Category extends Model
{
    protected $table = 'categories';

    public function pharmacies()
    {
        return $this->belongsToMany(Pharmacy::class, 'pharmacy_category', 'category_id', 'id');
    }

    public function medicines()
    {
        return $this->hasMany(Medicine::class);
    }
}

药房模式

class Pharmacy extends Model
{
    use SoftDeletes;
    protected $table = 'pharmacies';

    protected $appends = ['favourite'];

    public function categories()
    {
        return $this->belongsToMany(Category::class,'pharmacy_category','pharmacy_id','id');
    }

    public function getFavouriteAttribute()
    {
        if (!Auth::check()) {
            return 0;
        }
        return (FavouritePharmacy::where('user_id', Auth::user()->id)->where('pharmacy_id', $this->id)->count() == 1) ? 1 : 0;
    }
}

医学模型

class Medicine extends Model
{

    protected $appends = ['favourite'];

    public function orders()
    {
        return $this->belongsToMany(Order::class);
    }

    public function getFavouriteAttribute()
    {
        if (!Auth::check()) {
            return 0;
        }
        return (FavouriteMedicine::where('user_id', Auth::user()->id)->where('medicine_id', $this->id)->count() == 1) ? 1 : 0;
    }
}

【问题讨论】:

  • 你有代码吗?
  • 您的问题应该至少能证明收到回复的最小努力。在这种情况下,它不会。请向我们展示您为实现这一目标所做的尝试以及任何相关错误。
  • 我更新了问题
  • 我还没有写查询,因为我不知道如何开始它
  • 您应该创建pharmacymedicinepharmacy_medicinecategory。药学属于多药,药属于多药。医药属于范畴,范畴有很多医药。医学应该有category_id。获取药房时,您应该立即加载其他属性。

标签: laravel eloquent


【解决方案1】:

如果您想显示药房信息、药物类别以及这些关系,我会这样做:

$pharmacy = Pharmacy::find($id);

$categoriesWithMedicines = Category::whereHas('medicines', function($q) use($id) {
        $q->where('pharmacy_id', $id);
    })
    ->with(['medicines' => function($q) use($id) {
        $q->where('pharmacy_id', $id);
    }])
    ->get();

然后在一个视图中,您将拥有一个药房对象和一个类别列表,其中包含属于该药房的药品:

@foreach ($categoriesWithMedicines as $category)
    {{ $category->name }}
    @foreach ($category->medicines as $medicine)
        {{ $medicine->name }}
    @endforeach
@endforeach

【讨论】:

  • 我确实批准了它
猜你喜欢
  • 1970-01-01
  • 2021-12-10
  • 1970-01-01
  • 1970-01-01
  • 2020-10-08
  • 2021-12-07
  • 2017-10-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多