【问题标题】:Laravel 5.4 Auth::User() with relationship not workingLaravel 5.4 Auth::User() 与关系不起作用
【发布时间】:2018-12-17 19:19:28
【问题描述】:

我有 Table Vendors(用于测试 Auth 关系)和 Table Vendor_users,

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

还有这个数据库

在供应商模型中

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

和 Vendor_test 模型

 protected $table = 'vendors';

public function Vendor(){
    return $this->hasMany(Vendor::class);
}

【问题讨论】:

  • 有什么问题?
  • 关系不起作用
  • 那你为什么提到有问题的 Auth::user() 呢?
  • 我使用 dd(Auth::user()) 来检查该用户是否有供应商
  • 那么什么不是工作关系或身份验证?哪个模型有关于用户的信息?

标签: php laravel foreign-keys relationship


【解决方案1】:

从聊天和你当前的表结构来看,你应该有这样的关系

在供应商模型中

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

在 Vendor_contact 模型中

protected $primaryKey = 'vendContactId'; //check this 

public function vendor() 
{ 
  return $this->hasOne(Vendor::class, 'vendor_contact_id'); 
}

现在使用延迟加载来加载vendor_contact 关系

Auth::user()->load('vendor_contact');
dd(Auth::user());

【讨论】:

  • Yo rkj,在另一篇文章中,您的延迟加载解决了问题,但我有一个问题。为什么在环境测试中它不加载关系?它适用于调试/生产
  • 但 callng Auth::user()->relationshipname 适用于环境生产。知道为什么它不在环境测试中吗?
【解决方案2】:

根据您的讨论和表格结构, 在您的模型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);

【讨论】:

    猜你喜欢
    • 2015-05-13
    • 2018-01-03
    • 2018-12-09
    • 2017-06-29
    • 2018-09-03
    • 2020-09-05
    • 2018-03-07
    • 1970-01-01
    • 2017-08-01
    相关资源
    最近更新 更多