【问题标题】:laravel 6.0 belongsTo with ApplicationServicelaravel 6.0 belongsTo 与 ApplicationService
【发布时间】:2020-01-16 13:20:04
【问题描述】:

我是 laravel 框架的新手。我无法通过控制器中的价格获得工作药物。

我的模型;


use Illuminate\Database\Eloquent\Model;

class Medicine extends Model
{
    protected $table    = 'medicine';
    protected $fillable = [];
    protected $guarded  = [];

    public function withPrice()
    {
        return $this->hasMany('App\Models\MedicinePrice', 'medicine_id', 'id');
    }
}

在我的应用服务中;

    public function getRecentEntries()
    {
        $medicines = Medicine::orderBy('id','DESC')->take(10)->get()->toArray();
        dd($medicines);
        return $this->formatMedicine($medicines);
    }

药表:https://take.ms/EHrwd 药品价格表:https://take.ms/BMTJW

有什么帮助吗?非常感谢。

【问题讨论】:

    标签: laravel eloquent belongs-to


    【解决方案1】:

    您永远不会在代码中加载关系。您可以通过以下方式完成:

    Medicine::with('withPrice')->get();
    

    但是,with('withPrice') 听起来有点奇怪不是吗?我建议您将 Medicine 模型中的关系方法重命名为更漂亮的名称,例如 prices

    public function prices()
    {
        return $this->hasMany(MedicinePrice::class);
    }
    

    然后你可以用这样的价格取回药物:

    $medicines = Medicine::with('prices')->orderByDesc('id')->take(10)->get()->toArray();
    

    您可以在此处阅读有关预加载的更多信息:https://laravel.com/docs/6.x/eloquent-relationships#eager-loading

    【讨论】:

    • @FatihToprak 没问题!很高兴你现在明白了! :)
    • 你好 :) 我还有一个问题,public function category() { return $this->hasMany(MedicineCategoryMapping::class); } public function activeMatter() { return $this->hasOne(MedicineActiveMatterMapping::class); } 这是一些关系,问题是,我如何从另一个模型中获取其他关系数据? (在此代码中,类别关系)截图:take.ms/hQoZl
    • @FatihToprak A 有很多返回 Collection 实例。因此,您要么必须遍历集合,要么检索第一个模型。 $this->category->first()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2018-04-01
    • 2018-03-08
    相关资源
    最近更新 更多