Nested Many to Many Relationship in Laravel











up vote
0
down vote

favorite












I have the table structures as



products id



packs id



pack_products pack_id, product_id



pack_optional_products pack_id, product_id



So in the above table, pack will have 2 type of products, compulsory products and optional products, mean if customer buy the pack the products which are attached in that pack as compulsory will automatically ordered, but customer also can see if there is any optional product in the pack so customer can also buy that product too.



Now to manage orders I have the following table.



orders id, customer_id



order_pack order_id, pack_id



Here everything works fine, using attach method as $order->packs()->attach($pack["pack_id"]);



So here problem starts ( when I tried to add optional ordered products in the ordered pack), to manage optional products order, I have created the following table



order_pack_product order_id, pack_id, pack_optional_product_id



I have created a model as.





class Order extends Model
{
//
public function packs(){
return $this->belongsToMany(Pack::class)->withTimestamps()->withPivot('name');
}

public function parent() {
return $this->belongsTo(ParentCustomer::class);
}
}

class OrderPack extends Model
{
//
public function optionalProducts()
{
return $this->belongsToMany(PackOptionalProduct::class, 'order_pack_product')->withTimestamps();
}
}


And then I call the method as.



$order->packs()->optionalProducts()->attach($optionalProduct["pack_optional_product_id"]);


and I'm getting this error.




BadMethodCallException: Call to undefined method
IlluminateDatabaseEloquentRelationsBelongsToMany::optionalProducts()
in file
/.../....../laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php
on line 50




SO complete code related to above tables will be this.



$order = new Order();
$order->parent_id = $parent->id;
$order->school_id = $schoolId;
if($order->save()){
foreach($json["packs"] as $pack){
$order->packs()->attach($pack["pack_id"], ["child_name" => $pack["child_name"]]);
foreach($pack["optional_products"] as $optionalProduct){
$order->packs()->optionalProducts()->attach($optionalProduct["pack_optional_product_id"]);
}
}
return response()->json(["status" => "ok", "order_id" => $order->id]);
}else{
return response()->json(["status" => "failed"]);
}









share|improve this question




























    up vote
    0
    down vote

    favorite












    I have the table structures as



    products id



    packs id



    pack_products pack_id, product_id



    pack_optional_products pack_id, product_id



    So in the above table, pack will have 2 type of products, compulsory products and optional products, mean if customer buy the pack the products which are attached in that pack as compulsory will automatically ordered, but customer also can see if there is any optional product in the pack so customer can also buy that product too.



    Now to manage orders I have the following table.



    orders id, customer_id



    order_pack order_id, pack_id



    Here everything works fine, using attach method as $order->packs()->attach($pack["pack_id"]);



    So here problem starts ( when I tried to add optional ordered products in the ordered pack), to manage optional products order, I have created the following table



    order_pack_product order_id, pack_id, pack_optional_product_id



    I have created a model as.





    class Order extends Model
    {
    //
    public function packs(){
    return $this->belongsToMany(Pack::class)->withTimestamps()->withPivot('name');
    }

    public function parent() {
    return $this->belongsTo(ParentCustomer::class);
    }
    }

    class OrderPack extends Model
    {
    //
    public function optionalProducts()
    {
    return $this->belongsToMany(PackOptionalProduct::class, 'order_pack_product')->withTimestamps();
    }
    }


    And then I call the method as.



    $order->packs()->optionalProducts()->attach($optionalProduct["pack_optional_product_id"]);


    and I'm getting this error.




    BadMethodCallException: Call to undefined method
    IlluminateDatabaseEloquentRelationsBelongsToMany::optionalProducts()
    in file
    /.../....../laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php
    on line 50




    SO complete code related to above tables will be this.



    $order = new Order();
    $order->parent_id = $parent->id;
    $order->school_id = $schoolId;
    if($order->save()){
    foreach($json["packs"] as $pack){
    $order->packs()->attach($pack["pack_id"], ["child_name" => $pack["child_name"]]);
    foreach($pack["optional_products"] as $optionalProduct){
    $order->packs()->optionalProducts()->attach($optionalProduct["pack_optional_product_id"]);
    }
    }
    return response()->json(["status" => "ok", "order_id" => $order->id]);
    }else{
    return response()->json(["status" => "failed"]);
    }









    share|improve this question


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I have the table structures as



      products id



      packs id



      pack_products pack_id, product_id



      pack_optional_products pack_id, product_id



      So in the above table, pack will have 2 type of products, compulsory products and optional products, mean if customer buy the pack the products which are attached in that pack as compulsory will automatically ordered, but customer also can see if there is any optional product in the pack so customer can also buy that product too.



      Now to manage orders I have the following table.



      orders id, customer_id



      order_pack order_id, pack_id



      Here everything works fine, using attach method as $order->packs()->attach($pack["pack_id"]);



      So here problem starts ( when I tried to add optional ordered products in the ordered pack), to manage optional products order, I have created the following table



      order_pack_product order_id, pack_id, pack_optional_product_id



      I have created a model as.





      class Order extends Model
      {
      //
      public function packs(){
      return $this->belongsToMany(Pack::class)->withTimestamps()->withPivot('name');
      }

      public function parent() {
      return $this->belongsTo(ParentCustomer::class);
      }
      }

      class OrderPack extends Model
      {
      //
      public function optionalProducts()
      {
      return $this->belongsToMany(PackOptionalProduct::class, 'order_pack_product')->withTimestamps();
      }
      }


      And then I call the method as.



      $order->packs()->optionalProducts()->attach($optionalProduct["pack_optional_product_id"]);


      and I'm getting this error.




      BadMethodCallException: Call to undefined method
      IlluminateDatabaseEloquentRelationsBelongsToMany::optionalProducts()
      in file
      /.../....../laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php
      on line 50




      SO complete code related to above tables will be this.



      $order = new Order();
      $order->parent_id = $parent->id;
      $order->school_id = $schoolId;
      if($order->save()){
      foreach($json["packs"] as $pack){
      $order->packs()->attach($pack["pack_id"], ["child_name" => $pack["child_name"]]);
      foreach($pack["optional_products"] as $optionalProduct){
      $order->packs()->optionalProducts()->attach($optionalProduct["pack_optional_product_id"]);
      }
      }
      return response()->json(["status" => "ok", "order_id" => $order->id]);
      }else{
      return response()->json(["status" => "failed"]);
      }









      share|improve this question















      I have the table structures as



      products id



      packs id



      pack_products pack_id, product_id



      pack_optional_products pack_id, product_id



      So in the above table, pack will have 2 type of products, compulsory products and optional products, mean if customer buy the pack the products which are attached in that pack as compulsory will automatically ordered, but customer also can see if there is any optional product in the pack so customer can also buy that product too.



      Now to manage orders I have the following table.



      orders id, customer_id



      order_pack order_id, pack_id



      Here everything works fine, using attach method as $order->packs()->attach($pack["pack_id"]);



      So here problem starts ( when I tried to add optional ordered products in the ordered pack), to manage optional products order, I have created the following table



      order_pack_product order_id, pack_id, pack_optional_product_id



      I have created a model as.





      class Order extends Model
      {
      //
      public function packs(){
      return $this->belongsToMany(Pack::class)->withTimestamps()->withPivot('name');
      }

      public function parent() {
      return $this->belongsTo(ParentCustomer::class);
      }
      }

      class OrderPack extends Model
      {
      //
      public function optionalProducts()
      {
      return $this->belongsToMany(PackOptionalProduct::class, 'order_pack_product')->withTimestamps();
      }
      }


      And then I call the method as.



      $order->packs()->optionalProducts()->attach($optionalProduct["pack_optional_product_id"]);


      and I'm getting this error.




      BadMethodCallException: Call to undefined method
      IlluminateDatabaseEloquentRelationsBelongsToMany::optionalProducts()
      in file
      /.../....../laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php
      on line 50




      SO complete code related to above tables will be this.



      $order = new Order();
      $order->parent_id = $parent->id;
      $order->school_id = $schoolId;
      if($order->save()){
      foreach($json["packs"] as $pack){
      $order->packs()->attach($pack["pack_id"], ["child_name" => $pack["child_name"]]);
      foreach($pack["optional_products"] as $optionalProduct){
      $order->packs()->optionalProducts()->attach($optionalProduct["pack_optional_product_id"]);
      }
      }
      return response()->json(["status" => "ok", "order_id" => $order->id]);
      }else{
      return response()->json(["status" => "failed"]);
      }






      laravel many-to-many






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 17 at 16:19









      Jonas Staudenmeir

      11.4k2932




      11.4k2932










      asked Nov 17 at 11:51









      Asif Mushtaq

      1,3251534




      1,3251534
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote













          optionalProducts() is method of model, not of relation packs().



          Method $order->packs() - returns relation object, attribute $order->packs - returns collection of pack models.



          You need to iterate trough collection, to attach optionalProducts to every one pack model.



          foreach($pack["optional_products"] as $optionalProduct){
          foreach($order->packs as $item){
          $item->optionalProducts()->attach($optionalProduct["pack_optional_product_id"])
          }
          }


          Perhaps, this code will not correct the error, then you need to correct your code logic.






          share|improve this answer










          New contributor




          IndianCoding is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.


















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














             

            draft saved


            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53350955%2fnested-many-to-many-relationship-in-laravel%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            0
            down vote













            optionalProducts() is method of model, not of relation packs().



            Method $order->packs() - returns relation object, attribute $order->packs - returns collection of pack models.



            You need to iterate trough collection, to attach optionalProducts to every one pack model.



            foreach($pack["optional_products"] as $optionalProduct){
            foreach($order->packs as $item){
            $item->optionalProducts()->attach($optionalProduct["pack_optional_product_id"])
            }
            }


            Perhaps, this code will not correct the error, then you need to correct your code logic.






            share|improve this answer










            New contributor




            IndianCoding is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.






















              up vote
              0
              down vote













              optionalProducts() is method of model, not of relation packs().



              Method $order->packs() - returns relation object, attribute $order->packs - returns collection of pack models.



              You need to iterate trough collection, to attach optionalProducts to every one pack model.



              foreach($pack["optional_products"] as $optionalProduct){
              foreach($order->packs as $item){
              $item->optionalProducts()->attach($optionalProduct["pack_optional_product_id"])
              }
              }


              Perhaps, this code will not correct the error, then you need to correct your code logic.






              share|improve this answer










              New contributor




              IndianCoding is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.




















                up vote
                0
                down vote










                up vote
                0
                down vote









                optionalProducts() is method of model, not of relation packs().



                Method $order->packs() - returns relation object, attribute $order->packs - returns collection of pack models.



                You need to iterate trough collection, to attach optionalProducts to every one pack model.



                foreach($pack["optional_products"] as $optionalProduct){
                foreach($order->packs as $item){
                $item->optionalProducts()->attach($optionalProduct["pack_optional_product_id"])
                }
                }


                Perhaps, this code will not correct the error, then you need to correct your code logic.






                share|improve this answer










                New contributor




                IndianCoding is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.









                optionalProducts() is method of model, not of relation packs().



                Method $order->packs() - returns relation object, attribute $order->packs - returns collection of pack models.



                You need to iterate trough collection, to attach optionalProducts to every one pack model.



                foreach($pack["optional_products"] as $optionalProduct){
                foreach($order->packs as $item){
                $item->optionalProducts()->attach($optionalProduct["pack_optional_product_id"])
                }
                }


                Perhaps, this code will not correct the error, then you need to correct your code logic.







                share|improve this answer










                New contributor




                IndianCoding is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.









                share|improve this answer



                share|improve this answer








                edited Nov 17 at 15:18





















                New contributor




                IndianCoding is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.









                answered Nov 17 at 14:23









                IndianCoding

                4597




                4597




                New contributor




                IndianCoding is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.





                New contributor





                IndianCoding is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.






                IndianCoding is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.






























                     

                    draft saved


                    draft discarded



















































                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53350955%2fnested-many-to-many-relationship-in-laravel%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

                    Alcedinidae

                    Origin of the phrase “under your belt”?