简体   繁体   中英

Laravel: How to make relationship accessor

I have relations in model UserTasks to Review model

public function reviews()
{
    return $this->hasMany(Review::class,'task_id');
}

I'm loading reviews using with

UserTasks::with('reviews');

And I want to format reviews relation output using accessors in UserTasks model

public function getReviewsAttribute($reviews)
{
    // FILTER AND FORMAT RELATION OUTPUT
    foreach ($reviews as &$review) {
        if ($review['active'] == true) {
            $review['cid'] = bcrypt($this->cid);
            $reviews = [$review];
        }
    }
    return $reviews;
}

Unfortunately, this does not work

Relationships loaded using with do not pay attention to accessor

I read that it is almost impossible, but maybe someone know the way to format loaded relations using accessors

If you want all reviews in UserTasks model than you can try this

public function getReviewsAttribute($reviews)
{
    $reviews = $this->reviews;
    foreach ($reviews as $rewiew) {
        // DO SOMETHING WITH REVIEWS
    }
    return $reviews; 
}

By $reviews = Review::all(); this you will get all reviews and you can do whatever you want to do.

Don't forget to add namespace at top of your model like use Review;(give your namespace)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM