为什么在雄辩地查询模型时会得到空值?

时间:2019-09-16 18:28:32

标签: laravel eloquent model

我有一个问题,当雄辩地查询模型时,我得到一个空值,我有两个模型User.phpProject.php,当我使用修补匠并使用User.php时检查数据是否与Project.php有关系我得到了我想要的,但是当我使用Project.php检查数据是否与User.php有关系时,我得到的是空值值。

这是我的Project.php代码:

<?php

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

class Project extends Model
{
    public $table = "project";

    protected $guarded = [];

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

这是我对User.php的代码:

<?php

namespace App;

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

class User extends Authenticatable
{
    use Notifiable;

    public function projects(){
        return $this->hasMany(Project::class);
    }
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

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

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

这是我在Tinker中的结果:

Query model User.php to Project.php

这是我使用修补程序和查询时的结果,如您所见,我的User.phpProject.php有关系,但是当我使用Project.php时,我得到的是空值。

enter image description here

2 个答案:

答案 0 :(得分:0)

您应该使用急切加载方式来加载父级关系:

Project::with('owner')->first()->owner

并确认外键正确

答案 1 :(得分:0)

您尝试过吗:

f

因为(引自文档):

  

口才通过检查关系方法的名称并在方法名称后加上public function owner() { return $this->belongsTo(User::class, 'user_id'); } 后跟主键列的名称来确定默认外键名称。

相关问题