【发布时间】:2017-04-02 00:59:20
【问题描述】:
如何从使用数据透视表连接的 2 个表中获取数据?例如,在我的情况下,我使用数据透视表(penulis 表)将用户表连接到日志表。现在我想获取属于特定用户的期刊数据。我试过这个:
$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');
});
}
查看作曲家:
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”。我不想使用 eloquent,我想通过视图作曲家传递数据。我已经用视图作曲家@Alexey 更新了问题