我的认证用户通过user模型中的关系分配了一个颜色。
我想去:
return Auth::color()->id;
返回登录用户的颜色id。
我该怎么做呢?
我也不能这样做:
Auth::user()->color()->id
或
Auth::user()->color->id
我得到Undefined property: Illuminate'Database'Eloquent'Relations'BelongsTo::$id
然而,所有的关系都是定义的。
我来自Laravel 4,我做错了什么?
<?php
namespace App'Models;
use Illuminate'Auth'Authenticatable;
use Illuminate'Database'Eloquent'Model;
use Illuminate'Auth'Passwords'CanResetPassword;
use Illuminate'Contracts'Auth'Authenticatable as AuthenticatableContract;
use Illuminate'Contracts'Auth'CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
use Authenticatable, CanResetPassword;
protected $table = 'users';
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
public function color() {
return $this->hasOne(''App'Models'Colour');
}
public function salesarea() {
return $this->belongsTo(''App'Models'Salesarea');
}
public function getNameAttribute() {
return $this->first_name." ".$this->last_name;
}
}
由于我还不能创建评论,我将把我的问题写在这里,
- 应该是一对多还是一对一?
- user_id列是否存在于您的颜色数据库表中?
如果是一对多,则需要检查是否:你的用户模型有这个函数
public function colors()
{
return $this->hasMany('App'Color');
}
你的Color模型有这个函数
public function user()
{
return $this->belongsTo('App'User');
}
如果是这样,你应该能做到Auth::user()->colors是一个颜色对象的集合
如果它应该是一对一的您需要检查您的用户模型是否有这个函数
public function color()
{
return $this->hasOne('App'Color');
}
你的颜色模型有这个函数
public function user()
{
return $this->belongsTo('App'User');
}
如果是这样,你应该能做到Auth::user()->color witch是一个颜色对象
如果您的用户表有一个color_id
列,那么您希望一个属于关系,而不是一个有一个。A有一个关系,其中另一个表将具有user_id
列(例如profiles
表,其中配置文件只能属于一个用户)。但在您的例子中,我假设一种颜色可以分配给多个用户,因此一个用户属于一种颜色,而一种颜色有许多用户。
在这种情况下,你需要改变你的关系:
namespace App;
use Illuminate'Database'Eloquent'Model;
class User extends Model
{
public function color()
{
return $this->belongsTo(Color::class);
}
}
您将能够从认证服务中查询颜色:
$color = Auth::user()->color;
还要注意你的模型命名,因为你在问题中使用了美式和英式英语的"color"拼写。