Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Getting certain details only from many-to-many relationship
  • Hi there,

    I'm a beginner at PHP and MVC frameworks and have already read an almost same question over here. But when I try the same with my project, I'm met with an error.

    1. A 'user' subscribes to 'books'.
    2. A 'book' may be subscribed to by many 'users'.

    The following is my implementation:

    if ($user = Model_User::query()->related('books')->where('id', '=', $user_id)) {
    $books = $user->books;

    But this throws me the following error:

    Fuel\Core\PhpErrorException [ Notice ]:
    Undefined property: Orm\Query::$books

    I can get my desired result, if instead, I use the following:

    $books = Model_Book::query()->related('users')->where('', $user_id)->get();

    But I would rather not get all the 'user' details into the array if possible. I assume this is a security issue. Any ideas as to what I'm doing wrong?
  • Your query for getting the books is missing the `->get()` at the end that's why it throws an exception for \Orm\Query because it still is an \Orm\Query-object and not a query result object.
  • If I change to:
    $books = $user->books->get();

    I still get the error:
    Fuel\Core\PhpErrorException [ Notice ]:
    Undefined property: Orm\Query::$books
  • That is not where ->get() is needed, it's in your query:

    if ($user = Model_User::query()->related('books')->where('id', '=', $user_id)->get()) {
    $books = $user->books;

  • Okay, now I'm getting a different error:
    Fuel\Core\PhpErrorException [ Notice ]:
    Trying to get property of non-object
  • get() always returns an array, even if there is only one result. If you want a single result only (i.e. apply LIMIT 1 to the query), use get_one() instead.

    With get(), $user will be an array of objects, causing $user->books to fail with that error.

Howdy, Stranger!

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

In this Discussion