3 回答

TA貢獻1784條經驗 獲得超8個贊
如果我沒記錯的話,我猜您正在嘗試創建一個新字段,該字段不存在于表中,但需要在其中使用一些邏輯動態創建,并且您希望將該字段傳遞給您的每個產品。
如果是這樣,我猜 Laravel Eloquent Accessor 將是在這種情況下使用的最佳選擇。在 Accessor 的幫助下,您可以創建任何類型的字段,并且可以像調用其他字段一樣調用它。
如需更多參考,請查看此https://laravel.com/docs/5.7/eloquent-mutators Laravel 文檔。
從 Laravel 文檔中挑選的樣本。
public function getFullNameAttribute()
{
return "{$this->first_name} {$this->last_name}";
}
現在我可以在我的控制器或刀片文件中使用 full_name,例如 $user->full_name,它會給我連接 first_name 和 last_name 的字符串。

TA貢獻2039條經驗 獲得超8個贊
首先在你的模型中添加這個以添加自定義字段
protected $appends = ['is_favorite'];
public function getIsFavoriteAttribute($value)
{
return $this->name; // whatever you want add here
}
但是,當您在應用關系并從關系中選擇時獲取其他模型詳細信息時會出現問題。

TA貢獻1853條經驗 獲得超6個贊
將屬性添加到$appends.
class MyModel extends Model {
...
/**
* The accessors to append to the model's array form.
*
* @var array
*/
protected $appends = ['extra'];
public function getExtraAttribute(){
return "Extra Value";
}
...
}
- 3 回答
- 0 關注
- 132 瀏覽
添加回答
舉報