【问题标题】:How to get relation 'table1' OR 'table2' OR 'table3' into one table in laravel?如何将关系“table1”或“table2”或“table3”放入laravel中的一个表中?
【发布时间】:2019-07-18 15:10:11
【问题描述】:

我是这里和 Laravel 的新手,请见谅。我有一个名为“产品”的表,该表通过多对一关系与“食谱”表相关(其中一个食谱有很多产品)。 -“食谱”表保留参考代码-这是我坚持的地方; '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 模型),我能够获取所有关系。 但是如果我列出所有产品并尝试获取它的配方,我必须使用一堆“if 和 else”。就是买不到这样的食谱;

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

还有我的“食谱”表:

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

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

【问题讨论】:

    标签: laravel laravel-5.8


    【解决方案1】:

    我认为 您可以让每个关系个体合并数组 喜欢

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

    【讨论】:

    • 感谢您的宝贵时间。这是有道理的,但它给出了一个错误。我想要的只是一个保存三个表中所有数据的变量。能稍微解释一下吗?
    • 类似的东西;集合不能分配给数组。当我尝试返回return array_merge($arr1,$arr2,$arr3)
    • 在get()之后添加->toArray();
    【解决方案2】:

    欢迎来到 SO。

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

    例子:

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

    所以,你可以做的是使用 pluck() 和 collapse() 来检索关系的结果:

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

    【讨论】:

    • 感谢您的宝贵时间。当我像这样实现你的代码时它会出错: $recipe->pluck('sodium_bicarbonate')->collapse() 错误是:“未定义的属性:stdClass::$sodium_bicarbonate。我认为'hasOne'关系返回一个数组而不是集合。我该怎么办?
    • 如果您不获取嵌套关系,请尝试使用 $recipe->sodium_bicarbonate,而不使用 collapse()pluck(),因为 pluck() 需要一个集合。
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-15
      • 1970-01-01
      • 2013-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 2019-05-22
      相关资源
      最近更新 更多