Yii2: What is the correct way to define relationships among multiple tables?

元气小坏坏 提交于 2019-12-13 18:53:33

问题


In a controller I have the following code:

public function actionView($id)
{
    $query = new Query;
    $query->select('*')
        ->from('table_1 t1')
        ->innerJoin('table_2 t2', 't2.t1_id = t1.id')
        ->innerJoin('table_3 t3', 't2.t3_id = t3.id')
        ->innerJoin('table_4 t4', 't3.t4_id = t4.id')
        ->andWhere('t1.id = ' . $id);
    $rows = $query->all();
    return $this->render('view', [
        'model' => $this->findModel($id),
        'rows' => $rows,
        ]);
}

See the db schema: https://github.com/AntoninSlejska/yii-test/blob/master/example/sql/example-schema.png

In the view view.php are displayed data from tables_2-4, which are related to table_1:

foreach($rows as $row) {
    echo $row['t2_field_1'];
    echo $row['t2_field_2'];
    ...
}

See: Yii2 innerJoin() and: http://www.yiiframework.com/doc-2.0/yii-db-query.html

It works, but I'm not sure, if it is the most correct Yii2's way.

I tried to define the relations in the model TableOne:

public function getTableTwoRecords()
{
    return $this->hasMany(TableTwo::className(), ['t1_id' => 'id']);
}
public function getTableThreeRecords()
{
    return $this->hasMany(TableThree::className(), ['id' => 't3_id'])
    ->via('tableTwoRecords');
}
public function getTableFourRecords()
{
    return $this->hasMany(TableFour::className(), ['id' => 't4_id'])
    ->via('tableThreeRecords');
}

and then to join the records in the controller TableOneController:

$records = TableOne::find()
    ->innerJoinWith(['tableTwoRecords'])
    ->innerJoinWith(['tableThreeRecords'])
    ->innerJoinWith(['tableFourRecords'])
    ->all(); 

but it doesn't work. If I join only the first three tables, then it works. If I add the fourth table, then I receive the following error message: "Getting unknown property: frontend\models\TableOne::t3_id"

If I change the function getTableFourRecords() in this way:

public function getTableFourRecords()
{
    return $this->hasOne(TableThree::className(), ['t4_id' => 'id']);
}

then I receive this error message: "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'table_4.t4_id' in 'on clause' The SQL being executed was: SELECT table_1.* FROM table_1 INNER JOIN table_2 ON table_1.id = table_2.t1_id INNER JOIN table_3 ON table_2.t3_id = table_3.id INNER JOIN table_4 ON table_1.id = table_4.t4_id"


回答1:


You should have to define key value pair in the relation eg:

class Customer extends ActiveRecord
{
    public function getOrders()
    {
        return $this->hasMany(Order::className(), ['customer_id' => 'id']); // Always KEY => VALUE pair this relation relate to hasMany relation
    }
}

class Order extends ActiveRecord
{
    public function getCustomer()
    {
        return $this->hasOne(Customer::className(), ['id' => 'customer_id']);
// Always KEY => VALUE pair this relation relate to hasOne relation
        }
    }

Now in your forth relation use:

public function getTableFourRecords()
{
    return $this->hasOne(TableThree::className(), ['id' => 't4_id']);
}

You can read more on ActiveRecord here




回答2:


Based on the answer of softark the simplest solution can look like this:

Model TableOne:

public function getTableTwoRecords()
    {
        return $this->hasMany(TableTwo::className(), ['t1_id' => 'id']);
    }

Model TableTwo:

public function getTableThreeRecord()
    {
        return $this->hasOne(TableThree::className(), ['id' => 't3_id']);
    }

Model TableThree:

public function getTableFourRecord()
{
    return $this->hasOne(TableFour::className(), ['id' => 't4_id']);
}

Controller TableOneController:

public function actionView($id)
{
    return $this->render('view', [
         'model' => $this->findModel($id),
    ]);
}

The view table-one/view.php:

foreach ($model->tableTwoRecords as $record) {
    echo ' Table 2 >> ';
    echo ' ID: ' . $record->id;
    echo ' T1 ID: ' . $record->t1_id;
    echo ' T3 ID: ' . $record->t3_id;
    echo ' Table 3 >> ';
    echo ' ID: ' . $record->tableThreeRecord->id;
    echo ' T4 ID: ' . $record->tableThreeRecord->t4_id;
    echo ' Table 4 >> ';
    echo ' ID: ' . $record->tableThreeRecord->tableFourRecord->id;
    echo ' <br>';
}

A solution based on the GridView is also possible.

Model TableTwo:

public function getTableOneRecord()
{
    return $this->hasOne(TableOne::className(), ['id' => 't1_id']);
}
public function getTableThreeRecord()
{
    return $this->hasOne(TableThree::className(), ['id' => 't3_id']);
}
public function getTableFourRecord()
{
    return $this->hasOne(TableFour::className(), ['id' => 't4_id'])
        ->via('tableThreeRecord');
}

The function actionView in TableOneController, which was generated with Gii for the model TableTwo was edited:

use app\models\TableTwo;
use app\models\TableTwoSearch;
...
public function actionView($id)
{
    $searchModel = new TableTwoSearch([
        't1_id' => $id, // the data have to be filtered by the id of the displayed record
    ]);
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

    return $this->render('view', [
         'model' => $this->findModel($id),
         'searchModel' => $searchModel,
         'dataProvider' => $dataProvider,
    ]);
}

and also the views/table-one/view.php:

echo GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
     'id',
     't1_id',
     'tableOneRecord.id',
     't3_id',
     'tableThreeRecord.id',
     'tableThreeRecord.t4_id',
     'tableFourRecord.id',
    ],
]);

See the code on Github.



来源:https://stackoverflow.com/questions/33387126/yii2-what-is-the-correct-way-to-define-relationships-among-multiple-tables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!