【问题标题】:Laravel 8 belongsTo relationship not returning data on User modelLaravel 8 belongsTo 关系不返回用户模型上的数据
【发布时间】: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)-&gt;settings; 时,我什么也没有。

【问题讨论】:

  • 你能显示你正在使用的功能吗?如果我没记错的话,通常你需要调用-&gt;with(...)函数,
  • 是的,我打电话给:Auth::user() 并希望我的用户和用户设置在那里,我也尝试过:User::where('id', Auth::id())-&gt;first(); 这也没有给我我的用户设置
  • 是的,因为设置不会自动检索...为此您必须调用 ->with() 方法:laravel.com/docs/8.x/eloquent-relationships#eager-loading
  • 要从已删除的答案中回答您的问题,您将问题解释为laravel.com/docs/8.x/eloquent-relationships#one-to-one 关系,因此您永远不会使用 hasMany()。

标签: php laravel eloquent


【解决方案1】:

关系设置:

class User extends Model
{
//some custom stuff
    /**
     * Get the phone associated with the user.
     */
    public function user_setting()
    {
        return $this->hasOne(UserSetting::class);
    }
}
class UserSetting extends Model
{
    //some custom things
    /**
     * Get the user that owns the comment.
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

之后您可以使用eager laoding by default,在您的情况下,您必须将$with = ['user_setting'] 添加到您的User 类中。

您也可以使用-&gt;with() 方法,因为您必须使用以下任一方法:

 User::with('user_setting')->find(Auth::id());
//or
Auth::user()->with('organisation')->first()

由于明显的开销,Laravel 不会在每次调用中加载关系值。因此,您要么定义要默认加载的关系,要么必须使用 -&gt;with() 方法来预先加载关系。

【讨论】:

  • 太棒了,现在在我的模型中使用$with
【解决方案2】:

将此方法添加到您的 User 模型中
您可以通过动态属性$user-&gt; user_setting 访问用户设置 在每个 User 模型实例上 欲了解更多信息 https://laravel.com/docs/8.x/eloquent-relationships#one-to-one

    public function user_setting(){
       return $this->hasOne(UserSetting::class);
}

【讨论】:

  • 这个答案没有解释为什么你应该这样做,这也不是正确的方法
  • 为什么@Aless55 这不是正确的方法?
  • 谁能确认这个解决方案是否有效?这可能对我也有帮助。
  • 你只需要尝试看看@James
  • 正确的做法是使用一对一的关系,然后通过-&gt;with()方法使用急切加载
猜你喜欢
  • 2016-02-29
  • 1970-01-01
  • 2016-03-31
  • 1970-01-01
  • 2016-01-13
  • 2023-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多