【问题标题】:Get data from 2 tables connected using a pivot table (Laravel 5.3)从使用数据透视表连接的 2 个表中获取数据(Laravel 5.3)
【发布时间】: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 更新了问题

标签: laravel laravel-5


【解决方案1】:

如果你想使用 Eloquent,你应该先设置belongsToMany() 关系:

class User extends Authenticatable
{

    public function journals()
    {
        return $this->belongsToMany('App\Journal');
    }

然后使用 eager loading 加载数据:

User::where('id', $userId)->with('journals')->first();

如果您不想使用 Eloquent 并且只需要日志:

$journal_ids = DB::table('penulis')->where('id_user', $userId)->get(['id_journal'])->toArray();
$journal_list = DB::table('journal')->whereIn('id', $journal_ids)->paginate(20);

或者使用 join() 来做同样的事情。

【讨论】:

  • 试过这个,给我错误“未定义的变量用户ID”。我不想使用 eloquent,我想通过视图作曲家传递数据。我已经用视图作曲家更新了问题
  • @AriandoMiller,要传递数据,您需要先获取数据。如果您收到undefined variable userID 错误消息,只需将其设置为$userId = 5 或类似$userId = auth()->user()->id 如果您想获取当前用户ID。如果您不想使用 Eloquent,请尝试我的答案中的非 Eloquent 代码。
  • 我都试过了,但它仍然没有显示属于特定用户的期刊数据。也许我搞砸了用户ID?我不想获取当前用户 id,但选择了用户 id,例如,如果我单击 Jon Doe 的个人资料,它将显示 Jon Doe 的联系人数据以及属于他的期刊
【解决方案2】:

如果您正在使用Laravel,为什么不使用Eloquent

首先在你的模型中定义relations

class User extends Model {

    public function journal(){
        return $this->belongsToMany('App\Journal', 'penulis', 'id_user', 'id_journal');
    }

}


class Journal extends Model {

    public function user(){
        return $this->belongsToMany('App\User', 'penulis', 'id_journal', 'id_user');
    }

}

当然,您需要在模型中分别使用table nametable columns 定义tablefillables

而要获取users相关的具体数据可以使用eloquent,

User::with('journal')->paginate(20);

这将加载 20 个 users(paginated) 和相关的 journal 数据。

要进一步了解雄辩的关系,请查看link

希望它能解决你的问题。

【讨论】:

  • 您确定您的数据透视表中有相关​​数据吗?因为如果你有那么它肯定会出现
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多