2
2

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 5 years have passed since last update.

Laravel5 Eloquentリレーションで発行されるSQLの確認方法

Last updated at Posted at 2019-10-31

とりあえずクエリビルダで使えるtoSql()してみるとよい。

hasOne、hasMany、belongsTo、belongsMany、hasManyThrouthなどを定義したメソッド名にtoSQLをつける。
特に外部キーカラム名の指定が複雑なhasManyThrouthは、これを見るだけでだいぶわかりやすい(個人の感想です)

php
App\User::find(1)->relayTarget()->toSql();

例えば以下のようにUserモデルのリレーション設定を確認できる。

Eloquent
class User extends Model
{
	protected $table = 'users';
	public $primaryKey = 'id';

	/**
	 * リレーション
	 */
	public function relayTarget()
	{
		return $this->belongsTo(RelayTargetModel::class, 'relayTarget_id');
	}
}
ターミナル
$ php artisan tinker
>>> App\User::find(1)->relayTarget()->toSql();
=> "select * from `relay_target` where `relay_target`.`relayTarget_id` = ?"
2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?