如何将关系“table1”或“table2”或“table3”放入laravel中的一个表中?

问题描述 投票:0回答:3

我是这里的新手,也是 Laravel 的新手,所以请原谅。我有一个名为“产品”的表,该表通过多对一关系与“食谱”表相关(其中一个食谱有很多产品)。 -“食谱”表保留参考代码-这就是我陷入困境的地方; “食谱”表与保存“真实”产品配方的三个不同表具有一对一的关系。这些桌子有不同的食谱内容,例如,

碱性表;

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

Acets 表;

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->
“三个配方表之一的内容”

还有我的“食谱”表:

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

我相信这很容易,只是缺少一些东西。请帮忙!预先感谢!

php laravel laravel-5.8
3个回答
1
投票

我认为 您可以通过合并数组来获取每个关系 喜欢

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

1
投票

欢迎来到SO。

如果关系设置正确,则可以使用“collection->pluck()”来检索其结果,无论不同关系中嵌套的深度如何。

示例:

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

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

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


0
投票

我稍微编辑了@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
这样的数据 感谢大家宝贵的时间和丰富的知识!

© www.soinside.com 2019 - 2024. All rights reserved.