【发布时间】:2021-08-16 21:48:40
【问题描述】:
我正在构建一个 Laravel 8 API,并希望在查询 User 模型时自动将 user_settings 加入到 user。
我的想法是我可以通过belongsTo 关系实现这一点,因为user_settings“属于”用户。
但是,当我将此附加到我的 UserSetting 模型并查询用户时,尽管 user_settings 表中有数据,但我没有看到任何附加到我的用户的用户设置。
我哪里错了?
型号:User
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class UserSetting extends Model
{
use HasFactory, SoftDeletes;
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'user_settings';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'user_id',
'theme',
'refreshButtonPlacement',
'animationSpeed',
'fetchTimeout'
];
/**
* Get the user that owns the comment.
*/
public function user()
{
return $this->belongsTo(UserSetting::class);
}
}
型号:User
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
use HasFactory, Notifiable, SoftDeletes;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'first_name',
'last_name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password'
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
'last_login_at' => 'datetime'
];
/**
* Get the identifier that will be stored in the subject claim of the JWT.
*
* @return mixed
*/
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* @return array
*/
public function getJWTCustomClaims()
{
return [];
}
}
我还尝试使用One To One 关系并在我的User 模型上定义了settings 方法,但在Tinker 中,当我运行User::findOrFail(1)->settings; 时,我什么也没有。
【问题讨论】:
-
你能显示你正在使用的功能吗?如果我没记错的话,通常你需要调用
->with(...)函数, -
是的,我打电话给:
Auth::user()并希望我的用户和用户设置在那里,我也尝试过:User::where('id', Auth::id())->first();这也没有给我我的用户设置 -
是的,因为设置不会自动检索...为此您必须调用 ->with() 方法:laravel.com/docs/8.x/eloquent-relationships#eager-loading
-
要从已删除的答案中回答您的问题,您将问题解释为laravel.com/docs/8.x/eloquent-relationships#one-to-one 关系,因此您永远不会使用 hasMany()。