从 laravel eloquent 中的多个关系中获取数据 | 珊瑚贝

get data from multiple relations in laravel eloquent


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

关系是这样的

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

medicines 表有 pharmacy_id 和 category_id 列,其他列

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

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

任何想法都可能有用

类别模型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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);
    }
}

药房模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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;
    }
}

医学模型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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;
    }
}

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


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

1
2
3
4
5
6
7
8
9
$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();

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

1
2
3
4
5
6
@foreach ($categoriesWithMedicines as $category)
    {{ $category->name }}
    @foreach ($category->medicines as $medicine)
        {{ $medicine->name }}
    @endforeach
@endforeach
  • 我确实批准了


来源:https://www.codenong.com/43076420/

微信公众号
手机浏览(小程序)
0
分享到:
没有账号? 忘记密码?