如何将 'table1' OR 'table2' OR 'table3' 转化为 table in laravel?

How to get relation 'table1' OR 'table2' OR 'table3' into one table in laravel?

我在这里和 Laravel 都是新手,所以请原谅。我有一个名为 'products' 的 table,这个 table 通过多对一关系与 'recipes' table 相关(其中一个食谱有很多产品)。 -'recipes' table 保留参考代码- 这就是我卡住的地方; 'recipes' table 与保存 "real" 产品配方的三个不同 table 具有一对一关系。那些 table 有不同的食谱内容,例如

碱性table;

   Schema::create('alkalines', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('recipe_id');
        $table->integer('sodium_bicarbonate');
        $table->timestamps();
    });

Acets table;

   Schema::create('acets', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('recipe_id');
        $table->integer('sodium_chloride');
        $table->integer('acetic_acid');
        $table->timestamps();
    });

如果我从其中一个开始(例如使用 Acet 模型),我能够获取所有关系。 但是 如果,我列出所有产品并尝试获取它的配方,我必须使用一堆“if 和 else”。只是无法得到这样的食谱;

$product->recipe-> "one of the three recipe tables' content"

还有我的'recipes'table:

Schema::create('recipes', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('ref');
        $table->timestamps();
    });

我相信这很容易,只是遗漏了一些东西。请帮忙!提前致谢!

我觉得 您可以获得每个关系单独的它们合并数组 喜欢

$arr1=Alkalines::with('recipe')->get()->toArray();
$arr2==Acets::with('recipe')->get()->toArray();
$arr3=***************************;
array_merge($arr1,$arr2,$arr3)

欢迎来到 SO。

如果关系设置正确,您可以使用 'collection->pluck()' 检索它们的结果,无论不同关系中的嵌套有多深。

示例:

$game->players->stats 将不起作用,因为 players 是一个没有 stats 属性、方法或字段的集合。

因此,您可以使用 pluck() 和 collapse() 来检索关系结果:

$game->players->pluck('stats')->collapse()

我稍微编辑了来自@mohamedhassan 的代码,它成功了!

public function solutionMerge()
{
    $arr1=Alkaline::with('recipe')->get();
    $arr2=Acet::with('recipe')->get();
    $arr3=Glucose::with('recipe')->get();

    $solutionMerge = collect([$arr1,$arr2,$arr3]);

    return $solutionMerge;
}

刚刚将数组分配到集合中。然后使用 collapse()。 现在,我可以获取 $solutionMerge->recipe->id 之类的数据 感谢大家宝贵的时间和渊博的知识!