php - How to index returned array by key with eager loading in Laravel Eloquent? -
i'm working on side project in trying implement "like" functionality user's posts. using laravel's orm , use eager loading make things easier, i'll outline issue below. information first, post.php model contains this:
public function likes() { return $this->hasmany('app\models\postlike', 'post_id', 'post_id'); }
the postcontroller.php implementing api call load posts , likes looked like:
$posts = post::with("likes")->where("group_id", "=", $group_id)->get();
an example json response posts api might this:
[ { "post_id":1, "group_id":1, "author_id":1, "text":"some text here.", "created_at":"2015-08-13 00:15:08", "updated_at":"2015-08-13 00:15:08", "likes":[ {"post_id":1,"user_id":1,"updated_at":"2015-08-14 03:05:48"} ] } ]
the issue "likes" not indexed user_id, have search through array determine if user has liked post or not, easier have indexed unique user_id key. yield like:
[ { "post_id":1, "group_id":1, "author_id":1, "text":"some text here.", "created_at":"2015-08-13 00:15:08", "updated_at":"2015-08-13 00:15:08", "likes":{ "1": {"post_id":1,"user_id":1,"updated_at":"2015-08-14 03:05:48"} } } ]
so ultimate question how index eager loading response 1 of columns returns?
in order achieve that, you'll need add post-processing step code index array id. easy using collection's helper method keyby().
what need accessor load relation if needed , reindex array. accessor can used in different scenarios, without eagerly loading relation, that's why needs handle relation loading if needed.
adding method post model should trick:
public function getlikesattribute() { return $this->getrelationvalue('likes')->keyby('user_id'); }
custom accessors take priority above relation definitions in cases that, when botu likes() , getlikesattribute() exist. that's why accessor called when $post->likes , reindex table.
Comments
Post a Comment