php - Fetch a Model's associations in Laravel to simplify creation/update -
i have movie model following associations (belongstomany):
actor
country
genre ...
when form posted, have data (skipping lot of details here):
'actors' => array(
'cary grant',
'grace kelly',
...
),
'genres' => array(
'drama',
...
),
...
i'd update()/store() controller function associate these models.
an actor name 'cary grant' may or may not exist , may or may not associated movie i'm editing. remove him movie, i'd need remove association. same genre , else.
so thought i'd basemodel , of once in there, this:
1. movie model's defined associations.
2. check if post data contains associations.
3. each of them, check if exist (if not create them) , return array of ids. column i'm checking 'name', configurable.
4. sync() ids.
for now, don't need add more stuff related model movie form (ex. actor's birthdate).
i'm stuck @ n.1 ($movie->getrelations() works existing movies) , in general i'm not sure if right approach. hints?
i've met same problem , in project:
instead of retrieving defined relations of models, white-listing relations can updated adding static member
movie::$editablerelations = ['actors', 'genres', 'countries'];loop through post data, , match
$editablerelationsarrays. if data of relation exists, following below steps, otherwise not touch relation.
step 3 , step 4 same yours.
Comments
Post a Comment