我对拉拉维尔很陌生,我无法在拉拉维尔文档和这里找到这个问题的答案。我想这只是一个如何搜索它的问题,因为我非常确定这是一个常见的情况。
我有两个模型处于关系中(这是一个简化的情况),我通过资源文件检索我需要的信息,但我无法了解如何正确存储或更新信息。下面是一个代码示例:
Models\Company.php
class Company extends Model
{
protected $fillable = [
'name', 'blablabla', 'country_id', 'blablabla2',
];
public function country() {
return $this->belongsTo(Country::class);
}
}
Models\Country.php
class Country extends Model
{
protected $fillable = [
'code', 'name', 'prefix', 'tax_code_id',
];
public function companies() {
return $this->hasMany(Company::class);
}
}
然后我有一个公司控制器文件来管理API请求:
Controllers\CompanyController.php
class CompanyController extends BaseController
{
public function index()
{
$companies = Company::paginate();
$response = CompanyResource::collection($companies)->response()->getData(true);
return $this->sendResponse($response, 'Companies retrieved successfully');
}
public function store(Request $request)
{
$input = $request->all();
$validator = Validator::make($input, $this->validation_rules);
if($validator->fails()){
return $this->sendError('Validation error.', $validator->errors());
}
$company = Company::create($input);
return $this->sendResponse($company->toArray(), 'Company added successfully.');
}
}
...
public function update(Request $request, Company $company)
{
$input = $request->all();
$validator = Validator::make($input, $this->validation_rules);
if($validator->fails()){
return $this->sendError('Validation error.', $validator->errors());
}
$company->update($input);
return $this->sendResponse($company->toArray(), 'Company updated successfully.');
}
我希望更新公司表中记录1 country_id字段,以便它与有效载荷匹配(因此从100到200),但这并没有发生。
我可以编辑前端逻辑,以便仅发送有效负载中的country_id,因为我不打算更新国家/地区表,并且所有这些附加信息都是多余的,但我想知道如何使用Laravel在控制器中管理它。
你介意帮我吗?提前致谢。
弑天下