我的用户模型中有两个关系:
public function role()
{
return $this->belongsTo(Role::class, 'role_id');
}
public function currency()
{
return $this->belongsTo(Currency::class, 'currency_id');
}
如果我尝试在控制器角色关系中使用它可以工作,但货币关系带来dd($ user)
$user = Auth::user()->currency;
$user = Auth::user()->role;
它必须与AUTH有关。谢谢您的帮助。
完整的用户模型:
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Auth\Notifications\ResetPassword;
use Hash;
/**
* Class User
*
* @package App
* @property string $name
* @property string $email
* @property string $password
* @property string $role
* @property string $remember_token
*/
class User extends Authenticatable
{
use Notifiable;
protected $fillable = ['name', 'email', 'password', 'remember_token',
'role_id', 'currency_id'];
/**
* Hash password
* @param $input
*/
public function setPasswordAttribute($input)
{
if ($input)
$this->attributes['password'] = app('hash')-
>needsRehash($input) ? Hash::make($input) : $input;
}
/**
* Set to null if empty
* @param $input
*/
public function setRoleIdAttribute($input)
{
$this->attributes['role_id'] = $input ? $input : null;
}
public function role()
{
return $this->belongsTo(Role::class, 'role_id');
}
public function currency()
{
return $this->belongsTo(Currency::class, 'currency_id');
}
public function sendPasswordResetNotification($token)
{
$this->notify(new ResetPassword($token));
}
}
我的货币型号:
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Traits\FilterByUser;
/**
* Class Currency
*
* @package App
* @property string $title
* @property string $symbol
* @property string $money_format
* @property string $created_by
*/
class Currency extends Model
{
use SoftDeletes, FilterByUser;
protected $fillable = ['title', 'symbol', 'money_format',
'created_by_id'];
/**
* Set to null if empty
* @param $input
*/
public function setCreatedByIdAttribute($input)
{
$this->attributes['created_by_id'] = $input ? $input : null;
}
public function created_by()
{
return $this->belongsTo(User::class, 'created_by_id');
}
}
答案 0 :(得分:1)
您需要将currency_id
设为整数而不是字符串:
$table->unsignedInteger('currency_id');
答案 1 :(得分:1)
你的意思是急切加载? 在用户模型中添加属性
protected $with = ['role','currency'];