Laravel User只有一个计划,可以通过关系访问该计划

时间:2018-06-18 07:47:57

标签: php laravel laravel-5.6

我的用户型号:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name','plan_id', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function plan()
    {
        return $this->hasOne('App\Plan');
    }
}

我在用户表中将plan_id作为外键,引用plan表中的id。

当我访问时,User::with('plan')->get();我无法获得计划,我错过了什么?

2 个答案:

答案 0 :(得分:1)

如果您在用户表中将plan_id作为外键,则引用计划表中的id。

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name','plan_id', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

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

答案 1 :(得分:0)

在您的用户模型中:

public function plan()
{
   return $this->hasOne('App\Plan','user_id','id');
}

在您的控制器中:

$users=User::with('plan')->get();