我在两个班级之间有一对多的关系。当我尝试通过热切的加载方式接收当属儿童时,由于某种奇怪的原因,它不起作用。根据以下说明,它应该起作用:https://laravel.com/docs/master/eloquent-relationships#eager-loading
Te表具有以下列(其中包括旧项,无权更改此选项)。 kasticket_.kassa_id
和kassa.code
互相引用:
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模型,但是又提出了一个额外的数据库请求:
$receipts = \App\ReceiptDetail::with('pos')->get();
foreach ($receipts as $receipt) {
dd($receipt->pos()->first());
}
从查询日志中,我看到以下内容:
select * from `kasticket`
select * from `kassa` where `kassa`.`code` in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
答案 0 :(得分:0)
如果您在主键和外键中未使用正确的名称,则需要正确添加关系
更改如下:
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');
}
答案 1 :(得分:0)
表的唯一标识符(kasticket_.kassa_id
和kassa.code
)是数据库中的字符串。我必须在Pos类中添加以下行:
/**
* Indicates if the IDs are auto-incrementing.
*
* @var bool
*/
public $incrementing = false;