FK 列未保存,Laravel
FK Columns not saved, Laravel
我尝试在数据库中插入一些 FK,但该列的值为空。
我尝试使用 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
]);
默认情况下,所有 Eloquent 模型都可以防止 mass-assignment。在使用 create
或 fill
方法之前,您需要在模型上指定 fillable
或 guarded
属性:
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
];
}
我尝试在数据库中插入一些 FK,但该列的值为空。 我尝试使用 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
]);
默认情况下,所有 Eloquent 模型都可以防止 mass-assignment。在使用 create
或 fill
方法之前,您需要在模型上指定 fillable
或 guarded
属性:
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
];
}