代码之家  ›  专栏  ›  技术社区  ›  story ks

laravel 5.4 auth::user()与关系不工作

  •  0
  • story ks  · 技术社区  · 7 年前

    我有表供应商(用于测试身份验证关系)和表供应商用户,

    但是我用 Auth::user() 不是关系

    enter image description here

    还有这个数据库

    enter image description here

    在供应商模型中

        protected $table = 'vendor_users';
     public function Vendor_test(){
            return $this->belongsTo(Vendor_test::class);
        }
    

    和供应商测试模型

     protected $table = 'vendors';
    
    public function Vendor(){
        return $this->hasMany(Vendor::class);
    }
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   DsRaj    7 年前

    根据你的讨论和表格结构, 在模型中添加relation函数 vendor_users 是的。

    protected $table = 'vendor_users';
    public function vendor_contact() 
    { 
       return $this->belongsTo(Vendor_contact::class, 'vendor_contact_id'); 
    } 
    

    使用 vendor_contact 然后检查

    $user = Auth::user()->with('vendor_contact')->first(); //  As you asked with for auth
    //OR
    $user = Auth::user()->load('vendor_contact'); // From the rkj answer as I found this good.
    // OR
    $user = Vendor::find(1)->with('vendor_contact')->first(); 
    dd($user);
    
        2
  •  3
  •   rkj    7 年前

    从chat和您当前的表结构来看,您应该有这样的关系

    在供应商模型中

    public function vendor_contact() 
    { 
      return $this->belongsTo(Vendor_contact::class, 'vendor_contact_id'); 
    }
    

    供应商联系模式

    protected $primaryKey = 'vendContactId'; //check this 
    
    public function vendor() 
    { 
      return $this->hasOne(Vendor::class, 'vendor_contact_id'); 
    }
    

    现在使用lazy-eager加载 vendor_contact 关系

    Auth::user()->load('vendor_contact');
    dd(Auth::user());
    
    推荐文章