从laravel雄辩的多个关系中获取数据

时间:2017-03-28 17:43:43

标签: laravel eloquent

我有以下表 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;
    }
}

1 个答案:

答案 0 :(得分: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
相关问题