私はループテーブルのためのお気に入り」機能を持っています。私はピボットテーブルでこれを達成しようとしています。しかし、今、私はすべての説得力でループをお気に入り化(favourited)ログインユーザを呼び出すための最も効率的な方法を見つけようとしています。どのように説得力を持つピボットテーブル内の特定のプロパティを持つすべてのアイテムを取得しますか?
ループテーブル:
Schema::create('loops', function(Blueprint $table) {
$table->increments('id');
$table->string('name', 35);
$table->string('loop_path', 255);
$table->string('FK_user_id');
});
ユーザテーブル:
Schema::create('users', function(Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('password', 60);
});
お気に入りテーブル:
Schema::create('favourites', function(Blueprint $table) {
$table->increments('id');
$table->integer('FK_user_id')->unsigned();
$table->integer('FK_loop_id')->unsigned();
});
Loop.php:
class Loop extends Model {
protected $table = 'loops';
public $timestamps = true;
public function user()
{
return $this->belongsTo('App\User','FK_user_id','id');
}
public function favourites()
{
return $this->belongsToMany('App\User', 'favourites', 'FK_loop_id', 'FK_user_id');
}
}
これは私が今これを達成する方法であるが、効率的でいないようです:
$loops = Loop::with('favourites')->
with('user')->get();
$favouritedLoops = array();
foreach($loops as $loop)
{
//check if logged in user has favourited this
$user_favorites = Favourite::where('FK_user_id', '=', Auth::user()->id)
->where('FK_loop_id', '=', $loop->id)
->first();
if ($user_favorites != null)
{
array_push($favouritedLoops, $loop);
}
}
return Response::json($favouritedLoops);
は、あなたがこのように意味しますか? –