Laravel 5.8更新雄辩的模型并在一行中调用访问器?

时间:2019-04-29 17:18:43

标签: php laravel laravel-5 eloquent laravel-5.8

我有一个contact_info_scopes表,范围之一是“默认”,它可能是最常用的范围,因此我正在创建访问器

public function getDefaultScopeIdAttribute()
{
    return $this::where('contact_info_scope', 'Default')
        ->first()
        ->contact_info_scope_uuid;
}

获取defaultScopeId,并想知道如何更新ContactInfoScope模型并在一行中访问它。我知道我可以更新它:

$contactInfoScope = new ContactInfoScope();

然后访问它:

$contactInfoScope->defaultScopeId;

但是我想在一行中做到这一点而不必将类存储在变量中。也可以采用其他任何创新的方式来解决此问题,因为在这里访问器可能并不是理想的选择!我只需要创建一个公共函数(而不是作为访问器)就可以了,但是在一行中调用它会遇到同样的问题。谢谢:)

2 个答案:

答案 0 :(得分:1)

如果您在实例的构造函数方法中返回实例,则应该能够调用该模型并链接该值

(new ContactInfoScope)->defaultScopeID

没有在Laravel中尝试过,但可以在普通ol PHP中使用

答案 1 :(得分:0)

//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(用户::查找(1)->图像);