Campaign在我的Laravel 8 專案中我有一個名為專欄對此并不重要。
我想在我的Campaign模型中添加一些默認的鍵/值對,例如:dropdown_is_open并且應該有一個默認值false。
我遇到了模型的默認屬性并嘗試添加它,但在物件上看不到我的新鍵,我錯過了什么?
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Campaign extends Model
{
use HasFactory, SoftDeletes;
/**
* Indicates if the model's ID is auto-incrementing.
*
* @var bool
*/
public $incrementing = false;
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'campaigns';
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'campaign',
'template'
];
/**
* The model's default values for attributes.
*
* @var array
*/
protected $attributes = [
'dropdown_is_open' => false
];
}
控制器中的索引功能:
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$campaigns = Campaign::where('user_id', Auth::id())
->orderBy('created_at', 'desc')
->get();
if (!$campaigns) {
return response()->json([
'message' => "You have no campaigns"
], 404);
}
return response()->json([
'campaigns' => $campaigns
], 200);
}
我希望看到:
{
campaign: 'my campaign',
template: '',
dropdown_is_open: false <-- my key
}
Previously I was doing a foreach in my index function and adding the contextual keys on each item, but this would only show for the index function and I'd have to add it everywhere.
uj5u.com熱心網友回復:
我希望下面的內容有所幫助。
將其更改
my_custom_field為dropdown_is_open鍵(并從更改getMyCustomFieldAttribute為getDropdownIsOpenAttribute方法名稱)。
自定義屬性(或訪問器)
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model {
protected $appends = ['my_custom_field'];
public function getMyCustomFieldAttribute()
{
return false;
}
}
僅需要上述
$appends內容,以確保my_custom_field已預設/快取,甚至作為 JSON-Response 發送。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/433757.html
標籤:php laravel eloquent laravel-query-builder
上一篇:在laravel中使用變數無法從where條件中獲得結果
下一篇:將鍵相同的串列中的字典值求和
