首页 > 解决方案 > laravel 6.0 belongsTo 与 ApplicationService

问题描述

我是 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

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

标签: laraveleloquentbelongs-to

解决方案


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

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


推荐阅读