我在两个班级之间有一对多的关系。当我试图通过急切加载接收物品给孩子时,由于一些奇怪的原因,它不起作用。根据以下它应该工作:https://laravel.com/docs/master/eloquent-relationships#eager-loading
Te表具有以下列,以及其他列(遗留的,没有更改此列的选项)<代码>卡萨诺。kassa_id和kassa。代码
相互参照:
kasticket_.ticketnr, kasticket_.kassa_id, ...
kassa.code, ...
下面是一些经过简化的类。收据详情:
<?php
namespace App;
use App\Pos;
use Illuminate\Database\Eloquent\Model;
class ReceiptDetail extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'kasticket_';
/**
* The primary key for the model.
*
* @var string
*/
protected $primaryKey = 'ticketnr';
/**
* Get pos.
*/
public function pos()
{
return $this->belongsTo(Pos::class, 'kassa_id', 'code');
}
}
销售时点情报系统:
<?php
namespace App;
use App\ReceiptDetail;
use Illuminate\Database\Eloquent\Model;
class Pos extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'kassa';
/**
* The primary key for the model.
*
* @var string
*/
protected $primaryKey = 'code';
/**
* Get the receipt details.
*/
public function receiptDetails()
{
return $this->hasMany(ReceiptDetail::class, 'kassa_id', 'code');
}
}
结果是null,而不是Pos模型。在查询日志中,我可以看到它渴望加载但是:
$receipts = \App\ReceiptDetail::with('pos')->get();
foreach ($receipts as $receipt) {
dd($receipt->pos);
}
这给了我预期的Pos模型,但是已经提出了一个额外的DB请求:
$receipts = \App\ReceiptDetail::with('pos')->get();
foreach ($receipts as $receipt) {
dd($receipt->pos()->first());
}
从查询日志中,我看到以下内容:
select * from `kasticket`
select * from `kassa` where `kassa`.`code` in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
表的唯一标识符(kastick\uuu.kassa\u id
和kassa.code
)是数据库中的字符串。我必须在Pos类中添加以下行:
/**
* Indicates if the IDs are auto-incrementing.
*
* @var bool
*/
public $incrementing = false;
如果主键和外键中没有遵循正确的名称,则需要正确添加关系
像这样改变:
public function pos()
{
return $this->belongsTo(Pos::class,'foreign_key', 'local_key');
}
POS模型
public function receiptDetails()
{
return $this->hasMany(ReceiptDetail::class,'foreign_key', 'local_key');
}
更多信息