laravel 6.0 属于 ApplicationService

laravel 6.0 belongsTo with 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);
    }

Table 医学:https://take.ms/EHrwd Table / medicine_price : https://take.ms/BMTJW

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

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

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