【问题标题】:Eager loading not pulling relationship model急切加载不拉关系模型
【发布时间】:2020-01-21 21:35:08
【问题描述】:

Eager loading 不拉关系模型。

嗨,我使用的是 Laravel 6。我们的数据库是用 Zend 创建的,所以我们的模型有点奇怪;我必须设置主键。


// Customer model

protected $table = 'customer';
protected $primaryKey = 'Customer_ID';

/**
 * Get all appointments for the customer.
 */
public function appointments()
{
    return $this->hasMany('App\Appointment');
}

然后是约会


protected $table = 'appointment';
protected $primaryKey = 'Appointment_ID';

/**
 * Get the customer assigned to this appointment.
 */
public function customer()
{
    return $this->belongsTo('App\Customer');
}

现在,在控制器中:

$appointments = App\Appointment::with('customer')->take(5)->get();
return response()->json($appointments, 200);

数组有约会但客户为空:

{... Customer_ID: 1234, customer: null}

有什么想法吗?谢谢

【问题讨论】:

  • 客户的约会表的外键是哪个?
  • 这似乎很明显,但您肯定有您正在查询的约会的客户记录吗?
  • @GiacomoM 将是“Customer_ID”。它显示在约会结果中,因此关联就在那里。
  • @GBWDev 是的,但它显示为空。我迷路了。
  • 尝试在关系上指定主键、外键和表

标签: php laravel laravel-6


【解决方案1】:

在模型中创建关系时,可以告诉 laravel 哪个是外键的字段。
如果你不这样做,laravel 假设外键是id,这不是你的情况。

关系的定义应该变成:

public function customer()
{
    return $this->belongsTo('App\Customer', 'Customer_ID');
}

【讨论】:

  • 我想我在某个地方看到过这个。谢谢。我会在 15/30 分钟内尝试
  • 非常非常感谢!!
猜你喜欢
  • 2021-11-29
  • 2021-04-28
  • 2017-09-17
  • 2017-01-12
  • 2018-12-11
  • 1970-01-01
  • 2013-06-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多