【问题标题】:Laravel 5.8 newing up eloquent model and calling accessor in one line?Laravel 5.8 更新 eloquent 模型并在一行中调用访问器?
【发布时间】:2019-09-18 08:33:51
【问题描述】:

我有一个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;

但我想在一行中完成此操作,而不必将类存储在变量中。也开放任何其他创造性的方法来解决这个问题,因为访问器在这里可能并不理想!我可以只创建一个公共函数(而不是作为访问器),但会遇到在一行中调用它的相同问题。谢谢:)

【问题讨论】:

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


    【解决方案1】:
    //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(用户::find(1)->图像);

    【讨论】:

      【解决方案2】:

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

      (new ContactInfoScope)->defaultScopeID
      

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

      【讨论】:

        猜你喜欢
        • 2019-08-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-05
        相关资源
        最近更新 更多