I have an object, Request
, with a has-many relationship to RequestItem
(aliased to items
). So Request->items
is a Simple Resultset.
I see in the docs there is a way to update related records with update()
, and delete related records with delete()
. Is there any way to add related records in a similar fashion? I tried just $this->items[] = $Item, but got a "Cursor is an immutable ArrayAccess object" error.
I basically want to simply add a new related record to Request, and have Request->items reflect the addition. I was unable to find anything in the docs, which surprised me actually.
This question is over a year old at this point. New answers are not necessary or helpful
When you have a one to many relationship and you want add new items you have to set the array with the objects that do you want to add. example:
$Request = new Request();
// ... sets the attributes for Request object
$item1 = new RequestItem();
$item1->attr1 = $value1;
// ... add the attributes you want
$item2 = new RequestItem();
$item2->attr1 = $value2;
// ... and so on
$items = array($item1, $item2 /*, ... all that you need */);
$Request->items = $items;
if ($Request->save()) {
echo 'Good';
}
you must initialize belongsTo(Request) in the RequestItem model. when you add it, you create
$newItem = new RequestItem();
$newItem->setRequest($request);
$newItem->create();
then you will be able to get all items using $request->getItems();
please show me your db table structure with full realation's.
and you most use method in this page: http://docs.phalconphp.com/pt/latest/reference/models.html#defining-relationships
class Request extends \Phalcon\MVC\Model
{
public function initialize()
{
$this->hasMany('id', 'RequestItem', 'request_id');
}
}
$this->hasMany(' foreign key of main model ', ' related model name ', ' foreign key for related ');
class RequestItem extends \Phalcon\MVC\Model
{
public function initialize()
{
$this->belongsTo('request_id', 'Request', 'id');
}
}
$this->hasMany(' foreign key for related ', ' main model name ', ' foreign key of main model ');
As long as it's all set properly you can perform creation of related records like this:
class RequestsController extends \Phalcon\MVC\Controller
{
public function createItemsAction($RequestId)
{
$Request = Request::findFirst($RequestId);
$RequestItem = new RequestItem();
$RequestItem->Request = $Request;
$RequestItem->otherproperties = .....
}
}
Hope that is close to what you needed
Use following code to add that is save:
$user = new Users();
$success = $user->save($this->request->getPost(), array('name', 'email'));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.