0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

cakephp4 リレーション先のデータ取得・表示

Last updated at Posted at 2021-07-22

Every Qiita #20
のんびり独学初学者の毎日投稿チャレンジ 20日目
今回は・・・
cakephpでリレーション先のテーブルデータを取得した時の備忘録です。

modelでリレーションを設定する

公式チュートリアルの例に倣ってusersテーブルとarticlesテーブルで1対多のリレーションを設定してみます。
外部キーはuser_idです。

UsersTable.php
public function initialize(array $config): void
{
  parent::initialize($config)
  $this->hasMany('Articles',[
       'foreignKey'=>'user_id',
       'dependent'=>true,
     ]//foreignKeyはデフォルトで`テーブル名_id`
}
ArticlesTable.php
public function initialize(array $config): void
{
  parent::initialize($config)
  $this->belongsTo('Users',['foreignKey'=>'user_id']//foreignKeyはデフォルトで`テーブル名_id`
}

今回は外部キーがuser_idですので省略可能です。テーブル名_id以外でキーを設定する場合は任意で設定してください。
'dependent'をtrueに設定することで、再帰的にモデルを削除することができます。今回は特定のuserが削除されると、それに関連するarticlesも削除されます。

controllerでリレーション先のテーブルも取得する

今回はgetメソッドオプションのcontainを使って取得します。
一意のuser情報と関連するarticlesを一覧表示するためのクエリを設定します。

UsersController.php
public function view($id = null)
{
  $user = $this->Users->get($id, ['contain' => ['Articles']]);
  $this->set(compact('user'));
}

これでuserと関連するarticlesが取得できました。
viewで表示する時はforeachを使って表示します。

Users/view.php
foreach($user->articles as $article){
  echo $article->articlesテーブルの任意カラム
}

リレーション先のモデル名は大文字頭文字ですが、viewでは小文字ですので注意が必要です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?