1

I have an Eloquent model, that morphs to other Eloquent models, like this:

<?php

class Message extends Eloquent {

    public function message()
    {
        return $this->morphTo('message');
    }

}

The reason being, the application has many different types of messages. I know it’s not the most elegant of approaches, but it’s what I’ve been lumbered with by the previous developer.

So, my issue is: I need to only return Message instances, where the state column in the morphed-to message table matches a value. I have this query scope method in my Message model class:

public function scopeDeclinedMessages($query)
{
    return $query->with(array('message' => function ($q)
    {
        $q->where('state', '=', MessageState::DECLINED);

    }));
}

However, this doesn’t work, as it still returns Messages where the state in the morphed-to table doesn’t match the declined state.

For transparency, MessageState::DECLINED is a value of 2, but I’m getting messages back where the morphed-to table state column equals 0.

Martin Bean
  • 38,379
  • 25
  • 128
  • 201
  • Show the code, where you execute the query and the query as well (`DB::getQueryLog()` for example) – Jarek Tkaczyk Jul 01 '14 at 11:15
  • @deczo I don’t execute the query, Eloquent’s fluent query builder is used e.g. `$messages->declinedMessages();` – Martin Bean Jul 01 '14 at 12:32
  • Exactly, you get wrong results, according to your question, so show that code. – Jarek Tkaczyk Jul 01 '14 at 12:43
  • @deczo I don’t think I follow. I’ve given the code. I call my `declinedMessages()` scope, on the models listed above in the question. – Martin Bean Jul 01 '14 at 13:18
  • Well, my guess would be bug in `Eloquent`, since polymorphic relationships are buggy. I don't think you can do what you want, because `where` set in closure will be ignored. So check the queries run and you will know. – Jarek Tkaczyk Jul 01 '14 at 14:02
  • https://github.com/laravel/framework/issues/3986 – Andreas Jul 02 '14 at 08:22

0 Answers0