Laravel:hasOne返回null数组

时间:2018-05-16 20:49:39

标签: php laravel-5 relationship

我自己也找不到如何解决这个问题,所以是时候从知识渊博的人那里得到一些帮助了(再一次......)

上下文

“用户”表

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name', 40);
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
}

“userprofiles”表

public function up()
{
    Schema::create('userprofiles', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id');
        $table->string('avatar');
        $table->text('description');
        $table->string('social');
        $table->string('video');
        $table->timestamps();
    });
}

**播种机**

public function run()
    {
        $user = App\User::create([
            'name' => 'Unicorn',
            'email' => 'unicorn@gmail.com',
            'password' => bcrypt('password'),
            'superadmin' => 1,

        ]);

        App\Userprofile::create([
            'user_id' => $user->id,
            'avatar' => '/uploads/avatars/avatar.jpg',
            'description' => 'You just keep learning',
            'social' =>  'facebook.com',
            'video' =>  'youtube.com',
        ]);
    }

Userprofile模型(在App / Userprofile.php中)

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\User;

class Userprofile extends Model
{

    protected $fillable = [
        'user_id', 'avatar', 'description', 'social', 'video'
    ];


    public function user() {
       return $this->belongsTo('App\User', 'user_id');

    }
}

App / User.php中的用户模型

<?php

namespace App;

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

class User extends Authenticatable
{
    use Notifiable;

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

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

    public function userprofile() {
        return $this->hasOne('App\Userprofile', 'user_id'); 

    }

}

App/save/User.php 中的用户模型 与之前显示的相同但是没有公共功能userprofile() 如果将函数userprofile()添加到此User.php中,则代码可以正常工作。

用于显示结果的路线

Route::get('/test', function () {
    //dd(App\User::find(1)->userprofile);
    var_dump(App\User::find(1)->userprofile);
    var_dump(DB::getQueryLog());
});

结果本身

NULL array(0) { }

如果我只查询App\User::find(1) or App\Userprofile::find(1),那就完美了。但这种关系不是。我试图多次修改代码没有成功,我甚至添加了一个外键,而它应该没有它(如果我没错)。

感谢您的帮助!

0 个答案:

没有答案