So I'm creating a plugin wherein a customer can have grocery lists.
I have two created models - GroceryList and GroceryListItem. A grocery list contains one or many grocery list items. I can fetch data using GET /V1/grocerylist
that fetches grocery lists for the logged in costumer.
This is the example response:
// GET /V1/grocerylist
[
{
"list_name": "Daddy's grocery list",
"items": [
{
"name": "shampoo"
},
{
"name": "soap"
}
]
},
{
"list_name": "Mommy's grocery list",
"items": [
{
"name": "corned beef"
},
{
"name": "baby diapers"
}
]
}
]
This data, however, are seeded data. So, I haven't created an API endpoint for creating a grocery list (POST /V1/grocerylist
). My model classes already contain getter and setter methods (together with the corresponding API data interface, resource model classes, collection classes -- all barebones, just to make it work), but I have no idea how to associate GroceryListItem to GroceryList, and I'm not even sure I'm doing getItems()
method right.
And I think it's not as simple as this --
$this->setData('grocery_list_item', $items);
since this is not a simple field in a record (e.g. name of the grocery list).
My POST /V1/grocerylist
right now accepts this request body:
{
"data" :{
"list_name": "New grocery list",
"items": [
{
"name": "new item 1"
},
{
"name": "new item 2"
}
]
}
}
My expected results are:
- Return what's mentioned in
data
attribute (for testing purposes only) - Save the grocery list, together with the respective items to database
Here are some of the related files:
Model/GroceryListRepository.php
<?php
class GroceryListRepository implements GroceryListRepositoryInterface
{
/**
* @param int $customerId
*
* @return \Grocer\GroceryList\Api\Data\GroceryListInterface[]
*/
public function getList($customerId)
{
return $this->listCollectionFactory->create()->getItemsByColumnValue('customer_id', $customerId);
}
/**
* @param int $customerId
* @param \Grocer\GroceryList\Api\Data\GroceryListInterface $data
*/
public function createList($customerId, $data)
{
// TODO: Create grocery list
}
Model/GroceryList.php
<?php
/*...*/
use Grocer\GroceryList\Model\ResourceModel\GroceryListItem\CollectionFactory as ItemCollectionFactory;
/*...*/
class GroceryList extends AbstractModel implements GroceryListInterface
{
/*...*/
public function __construct(ItemCollectionFactory $itemCollectionFactory)
{
$this->itemCollectionFactory = $itemCollectionFactory;
}
/**
* @param GroceryListItemsInterface[] $items
* @return $this
*/
public function setItems(array $items = null)
{
// TODO: Set grocery list items to grocery list
}
/**
* @return GroceryListItemsInterface[]
*/
public function getItems()
{
return $this->itemCollectionFactory->create()
->getItemsByColumnValue('list_id', $this->getId());
}
/*...*/
}
Please enlighten me on this matter. Thank you.