在Laravel中找不到按类别名称列出的问题

bsxbgnwa  于 2023-01-27  发布在  其他
关注(0)|答案(2)|浏览(118)

我试图检索问题的基础上,他们所属的类别与此功能内我的问题控制器:

public function getByCategoryName($categoryName) {
        $category = Category::where('name', $categoryName)->first();
        return response($category->questions);

    }

问题是,即使$category设置正确,$questions也是空的,浏览器对我的请求返回一个空响应
表的创建方式如下:
问题表:

Schema::create('questions', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->string('title')->nullable(false);
            $table->string('content')->nullable(false);
            $table->integer('points')->default(0);
            $table->foreignId('user_id')
                ->constrained('users')
                ->onDelete('cascade');

            $table->string('category_name');
            $table->foreign('category_name')
                ->references('name')->on('categories')
                ->onDelete('cascade')
                ->onUpdate(null);

        });

类别表:

Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->string('name')->nullable(false);
            $table->unique('name');
        });

我有亲属关系函数HasMany和BelongsTo位于模型内部。
问题模型:

public function category(): BelongsTo
    {
        return $this->belongsTo(Category::class);
    }

类别型号:

public function question() : HasMany {
        return $this->hasMany(Question::class);
    }

我哪里做错了?

qvtsj1bj

qvtsj1bj1#

正如其他人所指出的。最好使用主ID键来进行有效的Map。然而,出于教育目的,这是可能的,我将解释。Eloquent通过检查关系方法的名称并在方法名称后添加_id来确定外键名称。因此,在本例中,Eloquent假设Question模型有一个category_id列。然而,因为Question模型上的外键不是category_id,所以我们必须将一个自定义的键名作为第二个参数传递给belongsTo方法:

public function category()
{
    return $this->belongsTo(Category::class, 'foreign_key'); // If we do not pass this eloquent thinks the foreign key is 'category_id'
}

// We need to pass our custom foreign key
public function category()
{
    return $this->belongsTo(Category::class, 'category_name');
}

Eloquent假设父模型Category将使用它的主ID关联,但由于这不是我们的情况,我们需要将父模型键关联到'name'列,因此我们需要将第三个参数传递给belongsTo方法,指定父表的自定义键:

public function category()
{
    return $this->belongsTo(Category::class, 'category_name', 'name');
}

您的完整解决方案应如下所示。

// Question model
public function category()
{
    return $this->belongsTo(Category::class, 'category_name', 'name');
}

// Category model
public function questions()
{
    return $this->hasMany(Question::class, 'category_name', 'name');
}
zpjtge22

zpjtge222#

更改此内容:

public function question() : HasMany {
        return $this->hasMany(Question::class);
    }

对此:

public function questions() : HasMany {
        return $this->hasMany(Question::class, 'category_name');
    }

相关问题