V
V
Viktor Yanyshev2018-03-01 22:10:23
Yii
Viktor Yanyshev, 2018-03-01 22:10:23

How to update a record in an intermediate table?

There are tables of news, projects and an intermediate table of news connection with the project and news. It is not entirely clear how this link () works, I would like an example specifically in my case. Now, tables:
news
id | title
projects
id | title
project_news
project_id | news_id
I create a post like this:

$model = new News(['scenario' => News::SCENARIO_CREATE]);
$project = new ProjectNews(); // Модель таблица project_news
$projectsList = Project::find()->all(); // Для вывода списка проектов
....
if($project->load(\Yii::$app->request->post())) {
 $project->news_id = $model->id;
 $project->save();
}
//  Всё ок, запись создаются, в проекте новости выводятся и т.д

But what if you need to change the project to which the news is attached?
$model = News::findOne(['id' => $id]);
$model->scenario = News::SCENARIO_UPDATE;

$project = ProjectNews::findOne(['news_id' => $id]); // Поиск записи в БД
$projectsList = Project::find()->all(); // Для вывода списка проектов

// Если
$projectId = \Yii::$app->request->post('ProjectNews');
$project->project_id = $projectId['project_id'];
$project->update(); // Ругается на отсутсвие PK

How to update a record in an intermediate table?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Fedorov, 2018-03-02
@qonand

Use ManyToMany Behavior it solves the tasks you need

D
Dmitry, 2018-03-01
@slo_nik

Good evening.
In the intermediate table, assign PK to two fields.
When creating a record, write data in both fields of the intermediate table.
When updating, use save(false) instead of update()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question