【问题标题】:laravel belongsTo not working with one to one relationlaravel 属于不使用一对一关系
【发布时间】:2018-05-24 20:54:41
【问题描述】:

我有两张桌子:

**plans:**
planId, plan_name

**Users:**
userId, user_name, password, planId

我试图获取选择所有用户的计划名称。

这是用户模型:

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class Users extends Authenticatable {

    public $timestamps = false;
    protected $table = 'users';
    protected $primaryKey = 'userId';

    protected $fillable = [
        'user_name',
        'password',
    ];

    protected $hidden = [
        '_token',
    ];

    public function plan()
    {
        return $this->belongsTo('App\Plans', 'planId');
    }

    public function validateCredentials( MyUserInterface $user, array $credentials ) {
        $plain = $credentials["password"] . $user->getAuthPasswordSalt();

        return $this->hasher->check( $plain, $user->getAuthPassword() );
    }
}

这是计划模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Plans extends Model {

    public $timestamps = false;
    protected $table = 'plans';
    protected $primaryKey = 'planId';

    protected $fillable = [
        'plan_name'
    ];

    protected $hidden = [
        '_token',
    ];

    public function users()
    {
        return $this->hasMany('App\Users', 'planId');
    }
}

当我使用时: \App\Users::get();

输出中没有关系...只有用户。

我能做什么?

我尝试使用 hasOne 和同样的问题...

很多

【问题讨论】:

  • 你真的在使用关系吗? IE。 App\Users::with(["plan"])-&gt;get();?除非您专门调用它们,否则不包括相关模型/集合。
  • tnx 这解决了我的问题

标签: php laravel frameworks


【解决方案1】:

你可以像这样急切地加载关系:

\App\Users::with('plan')->get();

或者添加一个$with 属性以always在您获取用户时立即加载它:

class Users extends Authenticatable
{
    protected $with = [
        'plan'
    ];
} 

如果你不想预先加载它,你可以像这样访问每个用户实例的计划:

$users = \App\Users::get();

foreach ($users as $user) {
    dd($user->plan);
}

【讨论】:

    猜你喜欢
    • 2021-06-30
    • 2014-06-24
    • 2018-09-27
    • 2014-08-22
    • 1970-01-01
    • 2018-10-03
    • 2019-11-21
    • 2018-05-29
    • 2013-10-21
    相关资源
    最近更新 更多