vendredi 1 septembre 2017

Is it possible to call a model function when using hasMany() in laravel 5?

Let say I have 2 models like this:

class Comment extends Model  {

    public function tagInsightPairs() {
        return $this->hasOne('App\Post', "post_id", 'id');
    }

    public function tags() {
        $this->tags = explode($this->tagString, ',');
        return $this;
    }
}

class Post extends Model {
    public function comments() {
        return $this->hasMany('App\Comment', 'id', 'post_id');
    }
}

In my controller,

class TestingController extends Controller {
    public function getIndex(Request $request) {
        $posts = Post::with('comments')->get();
        foreach($posts as $post) {
            $post = $post->tags();
        }
        dd($posts);
    }
}

I am using Laravel 5.2, and can upgrade if it is necessary. This is a fake case and in the actual case the tags() function is far more than an explode(), so moving the function SQL is not possible. Is there a way I can directly call the tags() function without making another foreach loop?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire