Laravel中的更新表和相关表 [英] updated table and related table in Laravel
本文介绍了Laravel中的更新表和相关表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Laravel中,我有关系:
In Laravel I have relation:
class Address extends Model
{
protected $fillable = [
'street', 'city', 'post_code', 'country', 'state',
];
public function companies() {
return $this->hasMany('App\Company');
}
}
class Company extends Model
{
protected $fillable = [
'name', 'nip', 'email', 'phone', 'address_id'
];
public function address() {
return $this->belongsTo('App\Address');
}
}
,在CompaniesController.php中,我想更新表.我的代码如下:
and in CompaniesController.php I want to do update tables. My code looks like this:
public function update(Request $request, $id)
{
Company::where('id', $id)->update([
'name' => $request->name,
'email' => $request->email,
'phone' => $request->phone,
'nip' => $request->nip,
]);
}
如何同时更新与该公司关联的地址?
How to also update the address associated with this company?
推荐答案
如果ID是您的主键,则应使用 find
而不是 where
将保证您只检索一行.
If the ID is your primary key, you should use find
instead of where
, as the former will guarantee that you only retrieve one row.
然后,您可以使用以下代码查询公司模型的关系:
You can then query the relationship of your Company model, using the following code:
$company = Company::find($id);
$company->update([
'name' => $request->name,
'email' => $request->email,
'phone' => $request->phone,
'nip' => $request->nip,
]);
$company->address()->update([
'street' => 'street value',
'city' => 'city value',
'post_code' => 'post_code value',
'country' => 'country value',
'state' => 'state value',
]);
请参考 laravel文档
这篇关于Laravel中的更新表和相关表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文