Laravel 5.8 更新 eloquent 模型并在一行中调用访问器?
Laravel 5.8 newing up eloquent model and calling accessor in one line?
我有一个 contact_info_scopes
table,其中一个范围是 'Default',这可能是最常见的范围调用,所以我正在创建一个访问器
public function getDefaultScopeIdAttribute()
{
return $this::where('contact_info_scope', 'Default')
->first()
->contact_info_scope_uuid;
}
获取 defaultScopeId
并想知道如何新建 ContactInfoScope
模型并在一行中访问它。我知道我可以更新它:
$contactInfoScope = new ContactInfoScope();
然后访问它:
$contactInfoScope->defaultScopeId;
但我想在一行中完成此操作,而不必将 class 存储在变量中。对解决这个问题的任何其他创造性方法也持开放态度,因为访问器在这里可能并不理想!我只需要创建一个 public 函数(而不是作为访问器)就可以了,但是在一行中调用它会遇到同样的问题。谢谢:)
如果您return实例在其构造方法中
,您应该能够调用模型并链接值
(new ContactInfoScope)->defaultScopeID
没有在 Laravel 中尝试过,但在普通 ol PHP
中可以使用
//LARAVEL
//write on model ----------------------------------
protected $appends = ['image'];
public function getImageAttribute()
{
$this->school_iMage = \DB::table('school_profiles')->where('user_id',$this->id)->first();
$this->studend_iMage = \DB::table('student_admissions')->where('user_id',$this->id)->first();
return $this;
}
//call form anywhere blade and controller just like---------------------------
auth()->user()->image->school_iMage->cover_image;
or
User::find(1)->image->school_iMage->cover_image;
or
Auth::user()->image->school_iMage->cover_image;
//可以测试
dd( User::find(1)->图像);
我有一个 contact_info_scopes
table,其中一个范围是 'Default',这可能是最常见的范围调用,所以我正在创建一个访问器
public function getDefaultScopeIdAttribute()
{
return $this::where('contact_info_scope', 'Default')
->first()
->contact_info_scope_uuid;
}
获取 defaultScopeId
并想知道如何新建 ContactInfoScope
模型并在一行中访问它。我知道我可以更新它:
$contactInfoScope = new ContactInfoScope();
然后访问它:
$contactInfoScope->defaultScopeId;
但我想在一行中完成此操作,而不必将 class 存储在变量中。对解决这个问题的任何其他创造性方法也持开放态度,因为访问器在这里可能并不理想!我只需要创建一个 public 函数(而不是作为访问器)就可以了,但是在一行中调用它会遇到同样的问题。谢谢:)
如果您return实例在其构造方法中
,您应该能够调用模型并链接值(new ContactInfoScope)->defaultScopeID
没有在 Laravel 中尝试过,但在普通 ol PHP
中可以使用//LARAVEL
//write on model ----------------------------------
protected $appends = ['image'];
public function getImageAttribute()
{
$this->school_iMage = \DB::table('school_profiles')->where('user_id',$this->id)->first();
$this->studend_iMage = \DB::table('student_admissions')->where('user_id',$this->id)->first();
return $this;
}
//call form anywhere blade and controller just like---------------------------
auth()->user()->image->school_iMage->cover_image;
or
User::find(1)->image->school_iMage->cover_image;
or
Auth::user()->image->school_iMage->cover_image;
//可以测试 dd( User::find(1)->图像);