問題描述
我有以下帶有關系的 Eloquent 模型:
I have the following Eloquent Models with relationships:
class Lead extends Model
{
public function contacts()
{
return $this->belongsToMany('AppContact')
->withPivot('is_primary');
}
}
class Contact extends Model
{
public function leads()
{
return $this->belongsToMany('AppLead')
->withPivot('is_primary');
}
}
數據透視表包含一個附加參數 (is_primary
),用于將關系標記為主要關系.目前,我在查詢聯系人時看到這樣的返回:
The pivot table contains an additional param (is_primary
) that marks a relationship as the primary. Currently, I see returns like this when I query for a contact:
{
"id": 565,
"leads": [
{
"id": 349,
"pivot": {
"contact_id": "565",
"lead_id": "349",
"is_primary": "0"
}
}
]
}
有沒有辦法將其中的 is_primary
轉換為布爾值?我已經嘗試將它添加到兩個模型的 $casts
數組中,但這并沒有改變任何東西.
Is there a way to cast the is_primary
in that to a boolean? I've tried adding it to the $casts
array of both models but that did not change anything.
推薦答案
由于這是數據透視表上的一個屬性,因此使用 $casts
屬性將不適用于 Lead
或 Contact
模型.
Since this is an attribute on the pivot table, using the $casts
attribute won't work on either the Lead
or Contact
model.
但是,您可以嘗試的一件事是使用自定義 Pivot
模型并定義了 $casts
屬性.自定義數據透視模型的文檔位于此處.基本上,您使用自定義創建一個新的 Pivot
模型,然后更新 Lead
和 Contact
模型以使用此自定義 Pivot
模型而不是基礎模型.
One thing you can try, however, is to use a custom Pivot
model with the $casts
attribute defined. Documentation on custom pivot models is here. Basically, you create a new Pivot
model with your customizations, and then update the Lead
and the Contact
models to use this custom Pivot
model instead of the base one.
首先,創建您的自定義 Pivot
模型,它擴展了基本的 Pivot
模型:
First, create your custom Pivot
model which extends the base Pivot
model:
<?php namespace App;
use IlluminateDatabaseEloquentRelationsPivot;
class PrimaryPivot extends Pivot {
protected $casts = ['is_primary' => 'boolean'];
}
現在,覆蓋 Lead
和 Contact
模型上的 newPivot()
方法:
Now, override the newPivot()
method on the Lead
and the Contact
models:
class Lead extends Model {
public function newPivot(Model $parent, array $attributes, $table, $exists) {
return new AppPrimaryPivot($parent, $attributes, $table, $exists);
}
}
class Contact extends Model {
public function newPivot(Model $parent, array $attributes, $table, $exists) {
return new AppPrimaryPivot($parent, $attributes, $table, $exists);
}
}
這篇關于如何投射 Eloquent Pivot 參數?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!