2012-02-29 91 views
1

我有两个模型PropertyAmenity他们之间的关系是多对多的。参考类是PropertyAmenity当我想插入单个记录到一个模型中对我来说很简单。主义 - 在多对多关系表中插入记录

插入到Property

$property = new Property(); 
$property->serial = 'SER09088'; 
$property->title = 'Some title'; 
$property->save(); 

,并插入记录到美化它是

$amenity = new Amenity(); 
$amenity->name = 'Swimming Pool'; 
$amenity->save(); 

我想要做的是增加现有设施,以Property其持有引用类PropertyAmenity记录例如类似的东西。

$property = new Property(); 
$property->serial = 'SER09088'; 
$property->title = 'Some title'; 
$property->PropertyAmenity->amenity_id[] = 1; 
$property->save(); 

当我尝试上面的代码中它给了我下面的异常不支持PropertyAmenity

添加的情况是我收集从形式的集体信息,从用户。例如用户输入与Property相关的所有值,并从表单中选择现有的Multiple Amenities并提交。我需要保存财产属性表和property_amenity表中的选定设施,包括两列property_idamenity_id,如何将此值插入教义?

回答

1

经过深入研究,我自己找到了解决方案,并且和预期的一样,它很容易实现。我唯一需要做的改变是。

从这个

$property->PropertyAmenity->amenity_id[] = 1; 

$property->PropertyAmenity[]->amenity_id = 1; 
$property->PropertyAmenity[]->amenity_id = 3; 
$property->PropertyAmenity[]->amenity_id = 5; 

和它的作品,希望它可以帮助别人:)