【问题标题】:How to do join in different names in Laravel?如何在 Laravel 中加入不同的名称?
【发布时间】:2019-08-07 06:55:40
【问题描述】:

我有两个名为usersbuys 的表:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('first_name');
        $table->string('last_name');
        $table->string('referral_code')->nullable();
        $table->integer('parent_id')->unsigned()->nullable();
        $table->string('mobile')->unique();
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
}



public function up()
{
    Schema::create('buys', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->bigInteger('product_id')->unsigned();
        $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
        $table->timestamps();
    });
}

我想加入 users.parent_idbuys.user_id。这是我当前的查询:

public function user ()
{
    return $this->hasOne(User::class);
}

我的查询:

$users = Buy::all()->where('parent_id', auth()->user()->id)->latest()->paginate(25);

但是我的查询抛出了这个:

SQLSTATE[42S22]:未找到列:1054 'where 子句'中的未知列 'parent_id'(SQL:从购买 where parent_id = 2 中选择 count(*) 作为聚合)

知道如何解决吗?

【问题讨论】:

  • 您的查询代码在哪里?您刚刚添加了关系。
  • 您放置用户方法的位置
  • 你想和users.parent_id一起加入buys.user_id吗?
  • @zahidhasanemon 我的查询已添加。

标签: php laravel


【解决方案1】:

在建立关系时,Laravel 期望外键名称将是方法名称 + _id 在您的情况下为 user_id 这对于本地键是可以的,但外键不是用户表上的 id ,所以你需要告诉 Laravel。所以试试这个:

public function user ()
{
    return $this->hasOne(User::class, 'parent_id', 'user_id');
}

-- 看到您的查询后编辑

您正在尝试使用您的购买模型中不存在的列。

$users = Buy::with('user')->where('user_id', auth()->user()->id)->latest()->paginate(25);

【讨论】:

    【解决方案2】:

    应该是这样的

    $users = Buy::where('user_id', auth()->user()->parent_id)->latest()->paginate(25);
    

    【讨论】:

      猜你喜欢
      • 2020-05-10
      • 1970-01-01
      • 2023-01-18
      • 2017-08-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多