ピボットテーブルを使用して2つのテーブルからデータを取得するにはどうすればよいですか?たとえば私の場合、私はピボットテーブル(ペニステーブル)を使用してジャーナルテーブルに接続されたユーザーテーブルを持っています。今私は特定のユーザーに属するジャーナルのデータを取得したいと思います。私はこれを試した:ピボットテーブル(Laravel 5.3)を使用して2つのテーブルからデータを取得
$journal_list = DB::table('journal')->where('id_user', '=','id_journal')->orderBy('id', 'desc')->paginate(20);
上記のコードは動作しません。以下は、私の移行は、次のとおりです。
Usersテーブル:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('username')->unique();
$table->string('userslug');
$table->string('nameslug');
$table->string('email')->unique();
$table->string('phone')->nullable();
$table->string('address')->nullable();
$table->string('password');
$table->rememberToken();
$table->enum('level', ['admin', 'author']);
$table->timestamps();
});
}
ジャーナルテーブル:
public function up() {
Schema::create('journal', function (Blueprint $table) {
$table->increments('id');
$table->string('title', 255);
$table->text('abstract');
$table->text('file');
$table->integer('id_edition')->unsigned();
$table->string('journalslug');
$table->timestamps();
});
}
Penulisテーブル(ピボットテーブル)
public function up()
{
Schema::create('penulis', function (Blueprint $table) {
// Create tabel penulis
$table->integer('id_user')->unsigned()->index();
$table->integer('id_journal')->unsigned()->index();
$table->timestamps();
// Set PK
$table->primary(['id_user', 'id_journal']);
// Set FK penulis --- user
$table->foreign('id_user')
->references('id')
->on('users')
->onDelete('cascade')
->onUpdate('cascade');
// Set FK penulis --- journal
$table->foreign('id_journal')
->references('id')
->on('journal')
->onDelete('cascade')
->onUpdate('cascade');
});
}
のView Composer:
public function boot()
{
View::composer('user/show', function ($view) {
$journal_list = User::where('id', $user_id)->with('journal')->first();
$view->with('journal_list', $journal_list);
});
}
あなたは自分の答えのコードを(View Composerの部分に)コピーしましたが、それはあなたのために働くかどうかは決して言いませんでした。それで、それは問題を解決しますか?そうでない場合は、エラーが発生しますか? –
私に「undefined variable userID」というエラーが表示されました。私は雄弁を使用したくないので、ビュー・コンポーザーを通してデータを渡したかったのです。私はビューの作曲家@Alexeyの質問を更新しました –