Laravel 如何获得关系';表1&x27;或';表2&x27;或';表3&x27;在拉威尔的一张桌子里?

Laravel 如何获得关系';表1&x27;或';表2&x27;或';表3&x27;在拉威尔的一张桌子里?,laravel,laravel-5.8,Laravel,Laravel 5.8,我是这里的新手,也在拉威尔,所以请原谅。我有一个名为“products”的表,该表通过多对一关系与“recipes”表相关(其中一个配方有很多产品)。-'“菜谱”表保留了参考代码——这就是我坚持的地方;“配方”表与保留“真实”产品配方的三个不同的表有一对一的关系。这些表格有不同的食谱内容,比如 碱性工作台 Schema::create('alkalines', function (Blueprint $table) { $table->bigIncrements('i

我是这里的新手,也在拉威尔,所以请原谅。我有一个名为“products”的表,该表通过多对一关系与“recipes”表相关(其中一个配方有很多产品)。-'“菜谱”表保留了参考代码——这就是我坚持的地方;“配方”表与保留“真实”产品配方的三个不同的表有一对一的关系。这些表格有不同的食谱内容,比如

碱性工作台

   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模型),我就能够获取所有关系但是如果我列出了所有的产品并试图获取它的配方,我必须使用一堆“如果”和“其他”。只是不能得到这样的食谱

$product->recipe-> "one of the three recipe tables' content"
和我的“食谱”表:

Schema::create('recipes', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('ref');
        $table->timestamps();
    });
我相信这很容易,只是错过了一些东西。请帮忙!提前谢谢

我想 您可以通过合并数组获得每个关系 像

欢迎来到SO

如果正确设置了关系,则可以使用“collection->pulk()”检索它们的结果,无论它们嵌套在不同的关系中有多深

例如:

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

所以,您可以使用pull()和collapse()检索关系的结果:


$game->players->pull('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

感谢大家,感谢你们宝贵的时间和渊博的知识

谢谢你抽出时间。当我像这样实现代码时,它给出了一个错误:$recipe->pull('nasodium_bicarbonate')->collapse()错误是:“未定义属性:stdClass:$碳酸氢钠。我认为“hasOne”关系返回的是数组而不是集合。我能做什么?如果您不获取嵌套关系,请尝试
$recipe->nasodium\u bicarbonate
,而不要使用
collapse()
pulk()
,因为pulk()需要收集。谢谢您的时间。这是有道理的,但它给出了一个错误。我所需要的是一个变量,它保存来自所有三个表的数据。你能解释一下吗;无法将集合分配给数组。当我尝试在get()之后返回
returnarray\u merge($arr1,$arr2,$arr3)
add->toArray()时;
array_merge($arr1,$arr2,$arr3)
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;
}