Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Load many-to-many relationship
  • Having trouble loading a relationship. Trying the following methods:
      //$locations = User::find_one_by_id($id)->related('locations')->get();
      $locations = User::find()->related('locations')->where('user_id', 3)->get_one();
      //$locations = User::query()->related('locations')->where('user_id', 3);
      //$locations = $data['user']->related('locations')->get();
      
      \Log::error("user locations: ".print_r($locations,true));
    

    Get the following error:
    Call to undefined method Model\User::related()

    Table is users_locations with user_id and location_id as the columns and primary key. The User model has the following defined:
     protected static $_many_many = array(
      'locations' => array(
       'key_from' => 'id',
       'key_through_from' => 'user_id',
       'table_through' => 'users_locations', 
       'key_through_to' => 'location_id', 
       'model_to' => 'Location',
       'key_to' => 'id',
       'cascade_save' => true,
       'cascade_delete' => false,
      )
     );
    

    Location model also has that variable defined but in the reverse direction. Using version 1.0 right now. Any help would be greatly appreciated!
  • Possibility 1, based on the error: You're not using the ORM but Model_Crud, the latter does just what it says: CRUD - no relational mapping. Possibility 2, based on the error and on the first method in your list: you get the object returned by User::find_one_by_id($id) on which you can't call related() - and it should be User::find_by_id($id) (that's a difference between the Orm & Model_Crud), which can be shortened to User::find($id). User::query()->related() and User::find()->related() (without params for find()) couldn't give that error as both return an Orm\Query object and thus wouldn't give that error. The last one could give that error if $data contains a Model\User object as the Orm\Model class doesn't have a related() method.
  • You are right Jelmer. Thanks for pointing me in the right direction!

Howdy, Stranger!

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

In this Discussion