Php 如何在Laravel中加入不同的名称?

Php 如何在Laravel中加入不同的名称?,php,laravel,Php,Laravel,我有两个名为users和buys的表: public function up() { Schema::create('users', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('first_name'); $table->string('last_name'); $table->string('r

我有两个名为
users
buys
的表:

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\u id
buys.user\u 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:选择count(*)作为来自购买的聚合,其中parent_id=2)


知道如何修复它吗?

在建立关系时,Laravel希望外键名称将是方法名称+
\u id
,在您的情况下
user\u 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);

在建立关系时,Laravel希望外键名称将是方法名称+
\u id
,在您的情况下
user\u 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);
应该是

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

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

您的查询代码在哪里?您刚刚添加了关系。您将用户方法放置在何处您想与
用户一起加入
购买.user\u id
。parent\u id
?@zahidhasanemon我的查询已添加。您的查询代码在何处?您刚刚添加了关系。您将用户方法放置在何处?是否要与
用户一起加入
购买.user\u id
。parent\u id
?@zahidhasanemon我的查询已添加。