laravel - 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
有什么帮助吗?非常感谢。
解决方案
您永远不会在代码中加载关系。您可以通过以下方式完成它:
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
推荐阅读
- python-2.7 - 加载 yaml 文件时编码错误
- javascript - 在特定时间段内对 div 执行操作(jQuery)
- mysql - 将聚合函数中的列与普通列进行比较 - MYSQL
- sql - 创建一个唯一约束/索引,考虑第二个表
- android - Android Fragments导航,回到backstack中的特定fragments
- javascript - 如何使用nodejs在电子邮件的html模板中嵌入图像?
- javascript - 如何通过按下按钮获得数组的平均值?
- jboss - Bundle 正在等待命名空间处理程序
- angular - 使用角度的对话流聊天机器人中的用户身份验证
- iteration - 如何解决 Ocaml 循环中的语法错误?