首页 > 解决方案 > FK 列未保存,Laravel

问题描述

我尝试在 db 中插入一些 FK,但该列的值为 null。我尝试使用 create(),但有多个值为 null,不知道为什么。

// Here I store value in LkpLocation if value is not in db
$lkp_location = new LkpLocation();

if(!is_null($request->lkp_location_text)){
    $exists = false;

    if($lkp_location->where('text', 'ILIKE', $request->lkp_location_text)->count() > 0){
        $exists = true;
    }
    if ($exists) {
        $lkp_location_id = $lkp_location->where('text', 'ILIKE', $request->lkp_location_text)->pluck('id')[0];
    }else{
        $lkp_location->fill([
            'text' => $request->lkp_location_text,
        ])->save();
        $lastInsertedId = $lkp_location->id;
        $lkp_location_id = $lastInsertedId;
    }
}
dump($lkp_location_id); // here I have the last ID

// Here I store values in Person table
$person = new Person();
$person->fill([
    //columns
    'lkp_location_id' => $lkp_location_id,
    //columns
]);

标签: laravellaravel-6

解决方案


默认情况下,所有 Eloquent 模型都可以防止批量赋值。在使用createorfill方法之前,您需要在模型上指定一个fillableorguarded属性:

use Illuminate\Database\Eloquent\Model;

class LkpLocation extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'text',
        //list other fillable columns here
    ];
}
class Person extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'lkp_location_id',
        //list other fillable columns here
    ];
}

推荐阅读