PHP/Laravel 获取具有特定列值的行

问题描述

链接图像中可以看出,我想查询具有相同章节编号的记录(跳过零)。假设我有 50 个章节,因此查询将产生 50 个集合,每个集合对应于某个列值,即章节编号。

data table with the same chapter numbers

如何将查询限制在我的 Laravel 控制器中?

解决方法

获取章节组,就像在图像中绘制

$chapters = Translation::where('chapter','!=',0)->get()->groupBy('chapter');
,

无分页:

texture_index

带分页:

$chapters = Translation::where('chapter',0)->get()->groupBy('chapter');

了解更多:https://laravel.com/docs/8.x/collections#method-groupby

,

在不了解您的项目设置的情况下,我会说:

$chapters = DB::table('translations')
    ->select('chapter')
    ->distinct()
    ->where('chapter','<>',0)
    ->get();

如果您使用 eloquent 模型:

$chapters = Translations::get()
    ->pluck('chapter')
    ->flatten()
    ->filter()
    ->values()
    ->all();
,

假设您有一个 Translation 模型并且想要使用 Eloquent

$chapters = Translation::where('chapter',0)->get()->groupBy('chapter');

上面说获取所有 Translation,其中与它们关联的 Chapter 不是 Chapter zero 并按 chapter 列对所有翻译进行分组。因此,如果您有 50 个章节,您将拥有 50 个集合,每个集合都包含其翻译。

如果您只想要特定的列,您可以使用 select() 并仅提供您想要的列。

,

在 Elequent 模型中,您可以创建与 'translations' 的 hasMany 关系,

class Chapter extends Model
{
    public function translations()
    {
        return $this->hasMany(Translation::class,'chapter');
    }

然后检索带有翻译的“章节”模型。

$chapters = Chapter::with('translations')->get()
,

这些答案中有很多是正确的,但我想我会提供不同的方法。

1。创建一个新表

考虑创建一个名为 chapters 的附加表。
使用以下命令执行此操作:

php artisan make:model Chapter -m

这将创建一个模型和迁移。
迁移将如下所示:

Schema::create('chapters',function (Blueprint $table) {
    $table->id();
    $table->integer('number')->unsigned();
    $table->string('heading');
    $table->timestamps();
});

2.将外键添加到旧表中

然后根据屏幕截图修改您的模型。从这里开始,我将和其他人一样假设这张表名为 translation,模型名为 Transaltion
您的新迁移应如下所示:

Schema::create('translations',function (Blueprint $table) {
    $table->id();
    $table->foreignId('chapters_id')->constrained()->onUpdate('cascade')->onDelete('cascade');
    $table->string('translation');
    $table->timestamps();
});

3.将关系添加到模型中

Translation 模型

public function chapters()
{
    return $this->belongsTo(Chapter::class);
}

Chapter 模型

public function translations()
{
    return $this->hasMany(Translation::class);
}

4.使用新关系

您现在可以查询每个标题,而不必使用 groupBy 或任何其他方法。
下面是其中一些示例。

4.1 我们有多少章?

Chapter::count();

4.2 第 1 章有多少个句子?

Chapter::where('number',1)->translations()->count();
// or if you want to get a Collection of them
Chapter::where('number',1)->translations;
// or if you just want a certain few columns
Chapter::where('number',1)->translations()->select('translation','sentence')->get();

4.3 如何获得所有章节和相应的翻译?

$chapters = Chapter::with('translations')->get();

然后在您的刀片视图中,执行以下操作:

@foreach ($chapters as $chapter)
    <h1>{{ $chapter->heading }}</h1>

    <p>Sentences:</p>
    @foreach ($chapter->translations as $sentence)
        <p>{{ $sentence }}</p>
    @endforeach
@endforeach

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...