Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
many_many ->get() and get_one()
  • Hello, I'm testing out the many_many orm thingy.
    I ve done a Category table, Posts table, posts_category table (i know wrong way to name tables but this is a test). Everything working well with ->get() .
    But with ->get_one(), when i ask for :
    $post = Model_Post::query()->related('categories')
       ->where('categories.id',1)
       ->get_one();
    
    it returns me "null" from var_dump($post).
    I've tried with categories.id = 2 and no issues, it returns what it should returns.
  • Thank you, i ve search the forum but maybe not enough
  • Search the forums, I've explained this a gazillion times before. In short the problem is that in order to write the query a tradeoff needs to be made: - Either you apply limits to the whole query in which case a get_one() would return one object of each type as most (only 1 row is fetched of the joined result). In this case your query would be possible but it would get at most one category while that's a many->many relations that should fetch more.
    - The solution we chose is to use a subquery to first apply the limit to the base model's table (Model_Post) and only then join with the relating table. This make it possible to limit the number of requested basemodel instances and still get all the relations. The downside is that this can fail because the limit on the base is done too soon for the condition on the relation. Which means that one row was selected which didn't have a relation that confirmed to your condition and thus nothing is returned. There's no perfect solution as far as I know, I'm open to other solutions but none I know of is without big downsides. Btw in your case it'd work by reversing it:
    $post = Model_Category::query()->related('posts')
       ->where('id', 1)
       ->get_one();
    

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion