laravel属于不与一对一的关系

时间:2018-05-24 20:54:41

标签: php laravel frameworks

我有两张桌子:

**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 \用户::得到();

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

我能做什么?

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

tnx很多

1 个答案:

答案 0 :(得分:3)

您可以急切加载这样的关系:

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

或者在您提取用户时,将<{1}}属性添加到始终急切加载:

$with

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

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