正如标题所示,我正在尝试更新hasMany()关系。我的应用程序中有一个Contacts和一个ContactsProperties模型。
联系人可以具有许多与它们相关联的属性。
我的模型设置如下:
Contacts模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Contacts extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'contacts';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'contact_name', 'first_name', 'last_name', 'email', 'telephone', 'created_at', 'updated_at'
];
/**
* Get properties associated with contact
*/
public function properties()
{
return $this->hasMany(ContactsProperties::class, 'contact_id');
}
}ContactsProperties模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ContactsProperties extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'contacts_properties';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'property_type', 'contact_id', 'address_line_1', 'address_line_2', 'city', 'county', 'postcode'
];
/**
* Get the contact that is assigned to the properties
*/
public function properties()
{
return $this->belongsTo(Contacts::class);
}
}我可以通过以下操作为联系人创建新属性:
$contact->properties()->createMany($request->address);效果很好。
我的问题是当我想更新属性时,编辑联系人时。我试过这样做:
$contact = Contacts::find($request->id);
// Update properties
$contact->properties()->saveMany($request->address);这将产生以下错误:
类型错误:传递给Illuminate\Database\Eloquent\Relations\HasOneOrMany::save()的参数1必须是照明\数据库\雄辩\模型的实例,数组给定,在第237行的/var/www/MyApp/2016/public/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php中调用
$request->address的值是一个数组:
Array
(
[0] => Array
(
[address_line_1] => test
[address_line_2] => Lane
[city] => Test
[county] => test
[postcode] => test
[property_type] => site
)
)有人知道如何实现我想做的事吗?
提前谢谢你。
发布于 2022-03-05 21:07:48
正如error说的,它需要模型实例,而不是数组。尝试从该请求输入创建一个ContactsProperties实例,然后您可以保存它,f.e。
$contactProperties = new ContactProperties($request->address);
$contact->properties()->saveMany($contactProperties);发布于 2022-05-06 15:47:36
saveMany()方法以模型的集合作为参数(参见文献资料)。您不能将关联数组传递给它。您从save()方法接收到的错误,该方法对集合中的每个模型调用一次,并期望Model作为参数。
saveMany()方法将为新模型插入新行,并更新现有模型的行。
似乎一次保存一个ContactProperties模型,在这种情况下可以直接调用save()方法,而不是saveMany(),但是您需要从请求中传递一个ContactProperties模型,而不是关联数组。
$contactProperties = new ContactProperties($request->address);
$contact->properties()->save($contactProperties);https://stackoverflow.com/questions/71365889
复制相似问题