【发布时间】:2021-05-23 09:49:34
【问题描述】:
我在两个模型之间有一个简单的关系:用户和处方。一个用户有很多处方。在 PrescriptionsController 中,当我尝试获取处方所属的用户时,使用 with() 时返回 null。
处方控制器
public function index()
{
$user_id = Auth::id();
$prescriptions = Prescription::with('user')->where('prescription_for', $user_id)->get();
return response()->json($prescriptions);
}
Eloquent 查询的结果:
[{"id":1,"prescription_for":1,"prescription_by":1,"prescription_content":"Paracetamol 120mg - O cutie. Mod administrare: 1 Dimineata | 0 Pranz | 0 Seara","created_at":"2020-10-13T17:33:35.000000Z","updated_at":null,"user":null}]
可以看到最后一个参数为空。 在我的用户模型中,我使用以下方法建立了关系:
public function prescriptions()
{
return $this->hasMany(Prescription::class);
}
以及处方模型:
protected $table = 'prescriptions';
public $primaryKey = 'id';
public $timestamps = true;
public function user()
{
return $this->belongsTo(User::class);
}
我正在使用 VueJs,所以我不能像在 Blade 文件中那样只做 $prescription->user->name,这就是我需要急切加载数据的原因。
我设置处方表的方式:
$table->id();
$table->unsignedBigInteger('prescription_for');
$table->foreign('prescription_for')->references('id')->on('users');
$table->unsignedBigInteger('prescription_by');
$table->foreign('prescription_by')->references('id')->on('users');
$table->string('prescription_content');
$table->timestamps();
对为什么会发生这种情况有任何想法吗?谢谢!
【问题讨论】:
-
试试这个
return $this->belongsTo(User::class, 'id', 'prescription_for'); -
再次检查您是否已通过身份验证。否则 Auth::id() 将没有值。
-
这行得通:return $this->belongsTo(User::class, 'id', 'prescription_for');你可以回答,我会标记为正确。非常感谢!