拉拉维尔'belongsTo'关系不起作用,不知道为什么



我有一个ClientCourier类,这是基本的迁移:

Schema::create('client_couriers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->timestamps();
$table->unsignedBigInteger('client_id');
$table->foreign('client_id')
->references('id')->on('clients')
->onDelete('cascade');
$table->string('name');
// the same client cannot have two couriers with the same name
$table->unique(['name', 'client_id']);
});

这是模型:

class ClientCourier extends Model
{
protected $guarded = [];
public function client() {
return $this->belongsTo(Client::class);
}
public function services() {
return $this->hasMany(ClientCourierService::class);
}
}

每个ClientCourier都可以有男人ClientCourierServices,因此hasMany关系。

以下是ClientCourierService的迁移:

Schema::create('client_courier_services', function (Blueprint $table) {
$table->bigIncrements('id');
$table->timestamps();
$table->unsignedBigInteger('client_id');
$table->foreign('client_id')
->references('id')->on('clients')
->onDelete('cascade');
$table->unsignedBigInteger('client_courier_id');
$table->foreign('client_courier_id')
->references('id')->on('client_couriers')
->onDelete('cascade');
$table->string('name');
$table->string('code', 64);
// the same courier cannot have two services with the same name
$table->unique(['name', 'client_courier_id']);
// the same client cannot have two services with the same code
$table->unique(['code', 'client_id']);
});

这是模型:

class ClientCourierService extends Model
{
protected $guarded = [];
protected $casts = [
'client_id' => 'integer',
'client_courier_id' => 'integer'
];
public function client() {
return $this->belongsTo(Client::class);
}
public function courier() {
return $this->belongsTo(ClientCourier::class);
}
}

因此,如您所见,我的client_courier_services表外键在列client_courier_id上带有client_couriers

现在,当我迭代我的服务并尝试从Service获取匹配的Courier时,它不起作用:

$services = ClientCourierService::get();
foreach($services as $service) {
$fromModel = $service->courier;
$fromDb = ClientCourier::where(['id' => $service->client_courier_id]);
// fromModel is null
// fromDb is the correct courier
}

我的其他关系有效。通过$courier->services从快递公司获得服务。从ClientCourier类或ClientCourierService类获取客户端有效。$service->courier;应该适用于所有帐户,但它没有,我很困惑。

我相信当您使用courier()作为方法名称时,它期望列名是courier_id因此没有结果的原因。尝试自己提供列名作为第二个参数。例如:

public function courier() {
return $this->belongsTo(ClientCourier::class, 'client_courier_id', 'id');
}

相关内容

最新更新