laravel - 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
]);
解决方案
默认情况下,所有 Eloquent 模型都可以防止批量赋值。在使用create
orfill
方法之前,您需要在模型上指定一个fillable
orguarded
属性:
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
];
}
推荐阅读
- c++ - C++:如何使用 decltype 从迭代器中获取类型
- reactjs - React:根据动态路径加载图像会导致错误
- javascript - How to make javascript function can use after dot
- marklogic - Marklogic URL encoding
- ethereum - 为什么我的合约中的address.transfer()函数只能发送1ether?
- apache-kafka - Phoenix Elixir kafka_ex 连接
- python - matplotlib bar chart with highlights values only
- laravel - Laravel version 5.7 root show index of page
- c# - .Net Core 2.2 / Kestrel / Swagger 禁用分块 / 编码
- python - 如何在 pandas 数据框中从 4 个级别创建两个 bin?