Complex Relation Model

Hi

I want to make a model relation in the relations method

For example in the customer model


public function relations() {

return array(

....

'recentOrder' => array(self::HAS_ONE, 'orders', 'customer_id', 'condition' => 'date_order=(SELECT MAX(date_order) FROM orders WHERE orders.customer_id=?how can I use t.id ?)'),

....

);

}

But I can’t find out how pass the customer id parameter in the condition.

I know that I could make a function to get the desired result but I am curious if it could be done in relations directly

Thanks

Maybe I’m missing something but you could probably just grab a customer then access that person’s latest order like this:




$customer = Customer::model()->find(...);

$recentOrder = $customer->recentOrder;


Customer Model Relations:

return array(

	'recentOrder' => array(self::HAS_ONE, 'orders', 'customer_id', 'order' => 'id DESC'),

)



Hi georaldc

Using ‘order’ (especially without index on the specific column) has performance issues, even using limit 1 (HAS_ONE). So your code works but I would like something different

Anyway, thank you for your response

Any other suggestion ?

I found a solution


'recentOrder' => array(self::HAS_ONE, 'orders', 'customer_id', 

'condition' => 'date_order=

(SELECT MAX(date_order) FROM orders WHERE orders.customer_id = recentOrder.customer_id)'), 

//where recentOrder.customer_id is a trick to filter only the specific customer model id

But I am not 100% sure that is correct…

I’m not sure if this is right, but I think you can use CActiveRecord::getTableAlias() in the relations() method.




public function relations()

{

    $tableAlias = $this->getTableAlias();


    return array(

        'recentOrder' => array(self::HAS_ONE, 'orders', 'customer_id',

            'condition' => "date_order=(SELECT MAX(date_order) FROM orders WHERE orders.customer_id={$tableAlias}.id})"

        ),

    );

}



If a developer can confirm this one way or the other, it would be very helpful.

Hi Keith,

Due to ‘HAS_ONE’ the $tableAlias could not be used

Instead of that we can use this one (and has the same results of the first one)




public function relations()

{


    return array(

        'recentOrder' => array(self::HAS_ONE, 'orders', 'customer_id',

            'join'=>'INNER JOIN customer ON (customer.id=orders.customer_id)'

            'condition' => "date_order=(SELECT MAX(date_order) FROM orders WHERE  orders.customer_id=customer.id})"

        ),

    );

}



Thanks for your suggestion :)