如何從使用數據透視表連接的2個表中獲取數據?例如,在我的情況下,我使用透視表(penulis表)將用戶表連接到日誌表。現在我想獲取屬於特定用戶的日記數據。我試過這個:從使用數據透視表連接的2個表中獲取數據(Laravel 5.3)
$journal_list = DB::table('journal')->where('id_user', '=','id_journal')->orderBy('id', 'desc')->paginate(20);
上面的代碼不起作用。下面是我的遷移:
用戶表:
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部分,但您從未說過它是否適用於您。那麼,它解決了這個問題嗎?如果沒有,你有任何錯誤? –
給了我錯誤「未定義的變量用戶ID」。我不想使用雄辯,我想通過視圖編輯器傳遞數據。我更新了視圖作曲家的問題@Alexey –