【问题标题】:Eloquent 'with()' returns null雄辩的 'with()' 返回 null
【发布时间】: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');你可以回答,我会标记为正确。非常感谢!

标签: laravel vue.js eloquent


【解决方案1】:

在您的prescriptions 表上,您的主键是prescription_for。如果父模型不使用id 作为其主键,或者您希望使用不同的列查找关联模型,您可以将第三个参数传递给belongsTo() 方法,指定父表的自定义键:

public function user()
{
    return $this->belongsTo(User::class, 'id', 'prescription_for');
}

【讨论】:

    猜你喜欢
    • 2020-02-18
    • 2018-01-14
    • 2018-12-21
    • 1970-01-01
    • 2017-07-29
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 2018-04-11
    相关资源
    最近更新 更多