I
I
Ivan Karabadzhak2014-01-04 20:32:43
Yii
Ivan Karabadzhak, 2014-01-04 20:32:43

How to correctly transfer data from two tables (yii, active record) to the view?

Interested in the correct approach to solving the following problem. Let's say I have two tables. In one list of customers, in the other list of customer orders. One-to-many relationship (one customer - many orders).
Let's say there is a view (view, view) in which you need to display data about the client and a list of his orders.
I usually do it like this:

$client = Client::model()->findByPk($id);
$orders = Order::model()->findAll('client_id = :client_id', array(':client_id' => $id);
$data['client'] = $client;
$data['orders'] = $orders;
$this->render('view_name', $data);

After that, in the view itself, it will not be difficult to display all the data.
I'm wondering if my solution is clumsy and there is a more elegant one? I assume that you can set up communication in models and get data even easier. And also worried about how clumsily I give data to the view?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
aavvbb, 2014-01-04
@Jakeroid

In the customer model

public function relations()
  {
       'orders'=>array(self::BELONGS_TO,'Order','client_id'),            
  }

Usage
$client = Client::model()->findByPk($id);
$this->render('view_name', array('client'=>$client, 'orders'=>$client->orders));

something in this style?

W
Wily, 2014-01-04
@wily

$client = Client::model()->findByPk($id);
$orders = Order::model()->findAll('client_id = :client_id', array(':client_id' => $id);
$this->render('view_name', array('client'=>$client, 'orders'=>$orders));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question