【问题标题】:Laravel Relationships: 3 ModelsLaravel 关系:3 个模型
【发布时间】:2018-12-07 17:09:39
【问题描述】:

我的 laravel 关系有问题。

我有 3 个模型:

城市 —(hasMany) —>诊所 —(hasMany) —>库存

Stock —(belongsTo) —>Clinic —(belongsTo) —>City

我需要得到所有有股票的城市,看起来像«Stock->cities»。我可以写sql查询:

SELECT ct.id, ct.name
FROM CfgCity as ct
RIGHT JOIN lr_clinics AS cl ON(ct.id=cl.city_id)
RIGHT JOIN lr_clinic_stocks AS st ON(cl.id=st.clinic_id)
WHERE st.deleted_at IS NULL
GROUP BY ct.id

但我想在 laravel-orm 中做出决定,因为它更具可读性,而且我不需要写行和表的名称。可能吗? 谢谢。

【问题讨论】:

  • 你需要更好地阅读文档。

标签: laravel eloquent


【解决方案1】:

根据您的问题,很明显cityclinic 有关系,而clinicstock 有关系,这意味着citystockclinic 有关系。你可以使用 laravel 关系来定义它。

城市模型

class City extends Model {

    public function clinics(){
       return $this->hasMany(Clinic::class);
    }

    public function stocks(){
       return $this->hasManyThrough(Stock::class, Clinic::class);
    }
}

获取数据

$cities = City::whereHas('stocks')->get();

详情可以查看https://laravel.com/docs/5.6/eloquent-relationships#has-many-through

【讨论】:

    猜你喜欢
    • 2020-03-07
    • 1970-01-01
    • 2021-08-29
    • 2018-10-17
    • 2023-02-16
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多