私はLaravel 5.4を使用しています。私は2台のテーブルdestination
とuser
とピボットテーブルdestination_user
を持っています。ピボットテーブルデータを使用してリレーションテーブルの情報を取得
先テーブル
---|------
id | name
---|------
1 | sth
ユーザテーブル
---|------
id | name
---|------
1 | sth
、最後にピボットテーブル
--------------|--------
destination_id| user_id
--------------|--------
1 | 1
2 | 1
3 | 2
私はdestinationUser
という名前のピボットテーブルのためのモデルを作成しました。
私destination
モデルは次のようになります。
<?php
namespace App\models;
use App\Models\User;
use App\Models\DestinationUser;
use App\Models\DestinationImage;
use Illuminate\Database\Eloquent\Model;
class Destination extends Model
{
protected $table = 'destinations';
public function user() {
return $this->belongsToMany('App\Models\User');
}
public function destinationUser() {
return $this->hasMany('App\Models\DestinationUser');
}
}
私は、ピボットテーブルを使用して、それぞれのユーザーのディテールを持つすべての宛先を取得したいです。
$destinations = $this->destination->with('user', 'destinationUser')
->whereHas('destinationUser', function($query) {
$query->where('user_id', user()->id);})
->paginate(20);
dd($destinations[0]->destinationUser);
は私にdestination id
とuser id
を与えるが、私は、ユーザーの詳細をしたい:私はこれで、これまで試してみました。どうすればこれを実現できますか?私は、クエリの実行速度を探していたとして、テーブルの間違った設計があった
class Destination extends Model
{
protected $table = 'destinations';
public function destinationUser() {
return $this->belongsToMany('App\User');
}
}
コントローラ
$destinations = $this->destination->with('destinationUser', function($query) {
$query->where('user.id', user()->id);})
->paginate(20);
多くの関係が必要ですhttps://laravel.com/docs/5.5/eloquent-relationships#many-to-many – madalinivascu
@madalinivascuより具体的にお聞かせください – vijayrana
ピボットテーブルのテーブル名は何ですか? – madalinivascu