Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
How to use ORM with same relations? (table_from_id and table_to_id related to same table.table_id)
  • I have a database table like this.
    `tables`
      `table_id` int(11)
      `table_name` varchar(255)

    And this is my table_log database table.
    `table_log`
      `table_log_id` int(11)
      `table_from_id` int(11) COMMENT 'refer to tables.table_id`
      `table_to_id` int(11) COMMENT 'refer to tables.table_id'

    I can use FuelPHP DB class like this.
    $result = \DB::select(\DB::expr('*, `table_from`.`table_name` AS `table_from_name`, `table_to`.`table_name` AS `table_to_name`'))
                    ->as_object()
                    ->from('table_log')
                    ->join(\DB::expr('`' . \DB::table_prefix('tables') . '` AS `table_from`'), 'left')
                        ->on(\DB::expr('`table_from`.`table_id`'), '=', 'table_log.table_from_id')
                    ->join(\DB::expr('`' . \DB::table_prefix('tables') . '` AS `table_to`'), 'left')
                        ->on(\DB::expr('`table_to`.`table_id`'), '=', 'table_log.table_to_id')
                    ->where('customer_id', $customer_id)
                    ->execute();
    It is work fine with DB class. I just call when loop $row->table_from_name and $row->table_to_name.

    How can i do this in ORM mode?
    Do i need to add manual select() like that?
    If not, How to write the relations property?
  • HarroHarro
    Accepted Answer
    Just define your relations as you would always do? ORM doesn't care what the target table of the relation is. And if you have multiple relations, just use different relation names.
  • I suggest using a simpler structure

    $result = \DB::select('tb.table_log_id','tb.table_from_id)
    ->from(array('table_log', 'tl'))
      ->join(array('tables', 't'))
        ->on('t.table_id', '=', 'tl.table_from_id')
      ->join(array('tables', 'tables_to'))
        ->on('tables_to.table_id', '=', 'tl.table_from_id')
    ->where('customer_id', $customer_id)->as_object()->excecute();

    Hope it helps.
  • @Harro
    Yep! I think that must only be the database table name.

    Something like this in model relations work!

    'table_from' => array(
        'key_from' => 'table_from_id',
        'key_to' => 'table_id',
        'model_to' => '\\Model_Tables',
    ),
    'table_to' => array(
        'key_from' => 'table_to_id',
        'key_to' => 'table_id',
        'model_to' => '\\Model_Tables',
    )

Howdy, Stranger!

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

In this Discussion