将额外的 table/data 加载到用户对象中

Load extra table/data into user object

在 Laravel 5.6 中,我试图将数据加载到用户对象中,因此我可以查看用户 credentials/settings 等

烦人的是我让它工作了,但由于某种原因现在它似乎已经停止了,我不确定我做了什么改变来破坏它。

无论如何我想加载两个表,accesssettings。它们都有 user_id 字段,相应的 user_id in.

在我的 User.php class 我有两个功能:

public function access() {
    return $this->hasMany(Access::class);   
}
public function settings() {
    return $this->hasOne(Settings::class);
}

不是 Use-ing 他们在 class(即 use \App\Access)的顶部,如果这有什么区别的话。

然后访问 class 看起来像:

namespace App;
use Illuminate\Database\Eloquent\Model;
class Access extends Model
{
    protected $table = "access";
}

和设置class非常相似:

namespace App;
use Illuminate\Database\Eloquent\Model;
class Settings extends Model
{
    protected $table = "settings";
}

但是,每当我尝试访问 Auth::user()->settingsAuth::user()->access 时,我都会收到 undefined index: 错误。这令人沮丧,因为就像我说的,我前几天让它工作了,但我不确定发生了什么变化。

您可以在这里尝试一些事情。首先,Lazy Eager Load loadMissing 的关系:

// settings
Auth::user()->loadMissing('settings');
// access
Auth::user()->loadMissing('access');

To load a relationship only when it has not already been loaded, use the loadMissing method

其次,您可以在查询用户时使用 with,尽管它与使用 auth facade 的相关性不高:

User::with(['settings', 'access'])->where('atribute', $value)->get();

最后,如果您始终希望每个 user 模型始终返回 settingsaccess 关系,请在 [=18] 上设置 with 属性=] 型号:

public class User {
    protected $with = ['settings', 'access'];
    ...
}

我通常也在模型上定义反向关系,因此 AccessSettings 将定义 BelongsTo 关系:

class Access extends Model
{
    protected $table = "access";

    public function user() {
        return $this->belongsTo(User::class);
    }
}

class Settings extends Model
{
    protected $table = "settings";

    public function user() {
        return $this->belongsTo(User::class);
    }
}