How Do Inverse Relationships Work in Laravel Eloquent?












0















I have two models/tables: publisher and campaign.



Publisher



id | name


Campaign



id | name | PubID


I created a relationship to get the Publisher's campaigns.



$this->hasMany(Campaign::class, 'PubID'); /* In Publisher Model */


I believe the above line will help me to retrieve relevant campaigns, but I'm confused about the inverse relationship.



As you can see, there is no key campaign_id inside the publisher table. Would the below relationship be enough for the inverse?



return $this->belongsTo('AppPublisher'); /* In Campaign Model */


Can someone kindly guide me? I would appreciate it.










share|improve this question

























  • You also need to specify the foreign key name in the belongsTo part in the same way you do in the hasMany part.

    – apokryfos
    Nov 28 '18 at 9:19











  • @apokryfos as I said there is no foreign key of campaign table inside publisher table

    – Script Lover
    Nov 28 '18 at 10:19











  • There's no need for one. In fact you can only have a foreign key on both tables if the relationship is one-to-one (which is not the case here). The PubID in Campaign is enough to define both ends of the relationship

    – apokryfos
    Nov 28 '18 at 10:34


















0















I have two models/tables: publisher and campaign.



Publisher



id | name


Campaign



id | name | PubID


I created a relationship to get the Publisher's campaigns.



$this->hasMany(Campaign::class, 'PubID'); /* In Publisher Model */


I believe the above line will help me to retrieve relevant campaigns, but I'm confused about the inverse relationship.



As you can see, there is no key campaign_id inside the publisher table. Would the below relationship be enough for the inverse?



return $this->belongsTo('AppPublisher'); /* In Campaign Model */


Can someone kindly guide me? I would appreciate it.










share|improve this question

























  • You also need to specify the foreign key name in the belongsTo part in the same way you do in the hasMany part.

    – apokryfos
    Nov 28 '18 at 9:19











  • @apokryfos as I said there is no foreign key of campaign table inside publisher table

    – Script Lover
    Nov 28 '18 at 10:19











  • There's no need for one. In fact you can only have a foreign key on both tables if the relationship is one-to-one (which is not the case here). The PubID in Campaign is enough to define both ends of the relationship

    – apokryfos
    Nov 28 '18 at 10:34
















0












0








0








I have two models/tables: publisher and campaign.



Publisher



id | name


Campaign



id | name | PubID


I created a relationship to get the Publisher's campaigns.



$this->hasMany(Campaign::class, 'PubID'); /* In Publisher Model */


I believe the above line will help me to retrieve relevant campaigns, but I'm confused about the inverse relationship.



As you can see, there is no key campaign_id inside the publisher table. Would the below relationship be enough for the inverse?



return $this->belongsTo('AppPublisher'); /* In Campaign Model */


Can someone kindly guide me? I would appreciate it.










share|improve this question
















I have two models/tables: publisher and campaign.



Publisher



id | name


Campaign



id | name | PubID


I created a relationship to get the Publisher's campaigns.



$this->hasMany(Campaign::class, 'PubID'); /* In Publisher Model */


I believe the above line will help me to retrieve relevant campaigns, but I'm confused about the inverse relationship.



As you can see, there is no key campaign_id inside the publisher table. Would the below relationship be enough for the inverse?



return $this->belongsTo('AppPublisher'); /* In Campaign Model */


Can someone kindly guide me? I would appreciate it.







php laravel eloquent relationship






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 28 '18 at 14:18









Jonas Staudenmeir

13.3k2936




13.3k2936










asked Nov 28 '18 at 9:06









Script LoverScript Lover

427




427













  • You also need to specify the foreign key name in the belongsTo part in the same way you do in the hasMany part.

    – apokryfos
    Nov 28 '18 at 9:19











  • @apokryfos as I said there is no foreign key of campaign table inside publisher table

    – Script Lover
    Nov 28 '18 at 10:19











  • There's no need for one. In fact you can only have a foreign key on both tables if the relationship is one-to-one (which is not the case here). The PubID in Campaign is enough to define both ends of the relationship

    – apokryfos
    Nov 28 '18 at 10:34





















  • You also need to specify the foreign key name in the belongsTo part in the same way you do in the hasMany part.

    – apokryfos
    Nov 28 '18 at 9:19











  • @apokryfos as I said there is no foreign key of campaign table inside publisher table

    – Script Lover
    Nov 28 '18 at 10:19











  • There's no need for one. In fact you can only have a foreign key on both tables if the relationship is one-to-one (which is not the case here). The PubID in Campaign is enough to define both ends of the relationship

    – apokryfos
    Nov 28 '18 at 10:34



















You also need to specify the foreign key name in the belongsTo part in the same way you do in the hasMany part.

– apokryfos
Nov 28 '18 at 9:19





You also need to specify the foreign key name in the belongsTo part in the same way you do in the hasMany part.

– apokryfos
Nov 28 '18 at 9:19













@apokryfos as I said there is no foreign key of campaign table inside publisher table

– Script Lover
Nov 28 '18 at 10:19





@apokryfos as I said there is no foreign key of campaign table inside publisher table

– Script Lover
Nov 28 '18 at 10:19













There's no need for one. In fact you can only have a foreign key on both tables if the relationship is one-to-one (which is not the case here). The PubID in Campaign is enough to define both ends of the relationship

– apokryfos
Nov 28 '18 at 10:34







There's no need for one. In fact you can only have a foreign key on both tables if the relationship is one-to-one (which is not the case here). The PubID in Campaign is enough to define both ends of the relationship

– apokryfos
Nov 28 '18 at 10:34














3 Answers
3






active

oldest

votes


















1














Yes, this is so called one to many relationship, which means one publisher has many campaigns. And the inverse is that a campaign belongs to a publisher.
So in order to get all the campaigns for the publisher you use:



Publisher::find($id)->campaigns;


In order to get what is the publisher of the campaign, you use:



Campaign::find($id)->publisher;


You don't need campaign_id inside the publisher table, that is known by the PubID in your campaign table.






share|improve this answer
























  • Alright, it's good explanation. But what about campaign model? Am I right in campaign model? Just want to confirm it. Thank you

    – Script Lover
    Nov 28 '18 at 10:21











  • @ScriptLover Yes, that's right. But keep in mind that whenever you use your custom name for the key such as PubID you will need to provide the name to the relationship, as you did with the hasMany, as the other guys are suggesting. A better naming convention is to use publisher_id in which case you won't need to manually add the foreign key column name.

    – nakov
    Nov 28 '18 at 10:31





















0














You ,eed to specify the foreign key name in the belongsTo



return $this->belongsTo('AppPublisher','PubID');


Laravel Relationships






share|improve this answer































    0














    You have two models and adding two foreign id. It is a many to many working. You just need add pivot table with campain_id and publiser_id



    It’s a perfect example of many-to-many relationship: one publisher can belong to several campains, and one campains can have multiple publisher.



    publishers



    ID | NAME



    campaigns



    ID | NAME



    campaign_publisher



    campain_id | publisher_id



    The final table in the list – campaign_publisher is called a “pivot” table, as mentioned in the topic title.



    So, option 1:



    class Campaign extends Model
    {
    /**
    * The products that belong to the shop.
    */
    public function publishers()
    {
    return $this->belongsToMany('AppPublisher');
    }
    }


    So, option 2:



    class Publisher extends Model
    {
    /**
    * The shops that belong to the product.
    */
    public function campaigns()
    {
    return $this->belongsToMany('AppCampaign');
    }
    }





    share|improve this answer























      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',
      autoActivateHeartbeat: false,
      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%2f53515711%2fhow-do-inverse-relationships-work-in-laravel-eloquent%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      Yes, this is so called one to many relationship, which means one publisher has many campaigns. And the inverse is that a campaign belongs to a publisher.
      So in order to get all the campaigns for the publisher you use:



      Publisher::find($id)->campaigns;


      In order to get what is the publisher of the campaign, you use:



      Campaign::find($id)->publisher;


      You don't need campaign_id inside the publisher table, that is known by the PubID in your campaign table.






      share|improve this answer
























      • Alright, it's good explanation. But what about campaign model? Am I right in campaign model? Just want to confirm it. Thank you

        – Script Lover
        Nov 28 '18 at 10:21











      • @ScriptLover Yes, that's right. But keep in mind that whenever you use your custom name for the key such as PubID you will need to provide the name to the relationship, as you did with the hasMany, as the other guys are suggesting. A better naming convention is to use publisher_id in which case you won't need to manually add the foreign key column name.

        – nakov
        Nov 28 '18 at 10:31


















      1














      Yes, this is so called one to many relationship, which means one publisher has many campaigns. And the inverse is that a campaign belongs to a publisher.
      So in order to get all the campaigns for the publisher you use:



      Publisher::find($id)->campaigns;


      In order to get what is the publisher of the campaign, you use:



      Campaign::find($id)->publisher;


      You don't need campaign_id inside the publisher table, that is known by the PubID in your campaign table.






      share|improve this answer
























      • Alright, it's good explanation. But what about campaign model? Am I right in campaign model? Just want to confirm it. Thank you

        – Script Lover
        Nov 28 '18 at 10:21











      • @ScriptLover Yes, that's right. But keep in mind that whenever you use your custom name for the key such as PubID you will need to provide the name to the relationship, as you did with the hasMany, as the other guys are suggesting. A better naming convention is to use publisher_id in which case you won't need to manually add the foreign key column name.

        – nakov
        Nov 28 '18 at 10:31
















      1












      1








      1







      Yes, this is so called one to many relationship, which means one publisher has many campaigns. And the inverse is that a campaign belongs to a publisher.
      So in order to get all the campaigns for the publisher you use:



      Publisher::find($id)->campaigns;


      In order to get what is the publisher of the campaign, you use:



      Campaign::find($id)->publisher;


      You don't need campaign_id inside the publisher table, that is known by the PubID in your campaign table.






      share|improve this answer













      Yes, this is so called one to many relationship, which means one publisher has many campaigns. And the inverse is that a campaign belongs to a publisher.
      So in order to get all the campaigns for the publisher you use:



      Publisher::find($id)->campaigns;


      In order to get what is the publisher of the campaign, you use:



      Campaign::find($id)->publisher;


      You don't need campaign_id inside the publisher table, that is known by the PubID in your campaign table.







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Nov 28 '18 at 9:18









      nakovnakov

      3,1102811




      3,1102811













      • Alright, it's good explanation. But what about campaign model? Am I right in campaign model? Just want to confirm it. Thank you

        – Script Lover
        Nov 28 '18 at 10:21











      • @ScriptLover Yes, that's right. But keep in mind that whenever you use your custom name for the key such as PubID you will need to provide the name to the relationship, as you did with the hasMany, as the other guys are suggesting. A better naming convention is to use publisher_id in which case you won't need to manually add the foreign key column name.

        – nakov
        Nov 28 '18 at 10:31





















      • Alright, it's good explanation. But what about campaign model? Am I right in campaign model? Just want to confirm it. Thank you

        – Script Lover
        Nov 28 '18 at 10:21











      • @ScriptLover Yes, that's right. But keep in mind that whenever you use your custom name for the key such as PubID you will need to provide the name to the relationship, as you did with the hasMany, as the other guys are suggesting. A better naming convention is to use publisher_id in which case you won't need to manually add the foreign key column name.

        – nakov
        Nov 28 '18 at 10:31



















      Alright, it's good explanation. But what about campaign model? Am I right in campaign model? Just want to confirm it. Thank you

      – Script Lover
      Nov 28 '18 at 10:21





      Alright, it's good explanation. But what about campaign model? Am I right in campaign model? Just want to confirm it. Thank you

      – Script Lover
      Nov 28 '18 at 10:21













      @ScriptLover Yes, that's right. But keep in mind that whenever you use your custom name for the key such as PubID you will need to provide the name to the relationship, as you did with the hasMany, as the other guys are suggesting. A better naming convention is to use publisher_id in which case you won't need to manually add the foreign key column name.

      – nakov
      Nov 28 '18 at 10:31







      @ScriptLover Yes, that's right. But keep in mind that whenever you use your custom name for the key such as PubID you will need to provide the name to the relationship, as you did with the hasMany, as the other guys are suggesting. A better naming convention is to use publisher_id in which case you won't need to manually add the foreign key column name.

      – nakov
      Nov 28 '18 at 10:31















      0














      You ,eed to specify the foreign key name in the belongsTo



      return $this->belongsTo('AppPublisher','PubID');


      Laravel Relationships






      share|improve this answer




























        0














        You ,eed to specify the foreign key name in the belongsTo



        return $this->belongsTo('AppPublisher','PubID');


        Laravel Relationships






        share|improve this answer


























          0












          0








          0







          You ,eed to specify the foreign key name in the belongsTo



          return $this->belongsTo('AppPublisher','PubID');


          Laravel Relationships






          share|improve this answer













          You ,eed to specify the foreign key name in the belongsTo



          return $this->belongsTo('AppPublisher','PubID');


          Laravel Relationships







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 28 '18 at 9:33









          KelvinKelvin

          428325




          428325























              0














              You have two models and adding two foreign id. It is a many to many working. You just need add pivot table with campain_id and publiser_id



              It’s a perfect example of many-to-many relationship: one publisher can belong to several campains, and one campains can have multiple publisher.



              publishers



              ID | NAME



              campaigns



              ID | NAME



              campaign_publisher



              campain_id | publisher_id



              The final table in the list – campaign_publisher is called a “pivot” table, as mentioned in the topic title.



              So, option 1:



              class Campaign extends Model
              {
              /**
              * The products that belong to the shop.
              */
              public function publishers()
              {
              return $this->belongsToMany('AppPublisher');
              }
              }


              So, option 2:



              class Publisher extends Model
              {
              /**
              * The shops that belong to the product.
              */
              public function campaigns()
              {
              return $this->belongsToMany('AppCampaign');
              }
              }





              share|improve this answer




























                0














                You have two models and adding two foreign id. It is a many to many working. You just need add pivot table with campain_id and publiser_id



                It’s a perfect example of many-to-many relationship: one publisher can belong to several campains, and one campains can have multiple publisher.



                publishers



                ID | NAME



                campaigns



                ID | NAME



                campaign_publisher



                campain_id | publisher_id



                The final table in the list – campaign_publisher is called a “pivot” table, as mentioned in the topic title.



                So, option 1:



                class Campaign extends Model
                {
                /**
                * The products that belong to the shop.
                */
                public function publishers()
                {
                return $this->belongsToMany('AppPublisher');
                }
                }


                So, option 2:



                class Publisher extends Model
                {
                /**
                * The shops that belong to the product.
                */
                public function campaigns()
                {
                return $this->belongsToMany('AppCampaign');
                }
                }





                share|improve this answer


























                  0












                  0








                  0







                  You have two models and adding two foreign id. It is a many to many working. You just need add pivot table with campain_id and publiser_id



                  It’s a perfect example of many-to-many relationship: one publisher can belong to several campains, and one campains can have multiple publisher.



                  publishers



                  ID | NAME



                  campaigns



                  ID | NAME



                  campaign_publisher



                  campain_id | publisher_id



                  The final table in the list – campaign_publisher is called a “pivot” table, as mentioned in the topic title.



                  So, option 1:



                  class Campaign extends Model
                  {
                  /**
                  * The products that belong to the shop.
                  */
                  public function publishers()
                  {
                  return $this->belongsToMany('AppPublisher');
                  }
                  }


                  So, option 2:



                  class Publisher extends Model
                  {
                  /**
                  * The shops that belong to the product.
                  */
                  public function campaigns()
                  {
                  return $this->belongsToMany('AppCampaign');
                  }
                  }





                  share|improve this answer













                  You have two models and adding two foreign id. It is a many to many working. You just need add pivot table with campain_id and publiser_id



                  It’s a perfect example of many-to-many relationship: one publisher can belong to several campains, and one campains can have multiple publisher.



                  publishers



                  ID | NAME



                  campaigns



                  ID | NAME



                  campaign_publisher



                  campain_id | publisher_id



                  The final table in the list – campaign_publisher is called a “pivot” table, as mentioned in the topic title.



                  So, option 1:



                  class Campaign extends Model
                  {
                  /**
                  * The products that belong to the shop.
                  */
                  public function publishers()
                  {
                  return $this->belongsToMany('AppPublisher');
                  }
                  }


                  So, option 2:



                  class Publisher extends Model
                  {
                  /**
                  * The shops that belong to the product.
                  */
                  public function campaigns()
                  {
                  return $this->belongsToMany('AppCampaign');
                  }
                  }






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 28 '18 at 10:43









                  Ismoil ShifoevIsmoil Shifoev

                  1,3221914




                  1,3221914






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53515711%2fhow-do-inverse-relationships-work-in-laravel-eloquent%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

                      A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

                      Calculate evaluation metrics using cross_val_predict sklearn

                      Insert data from modal to MySQL (multiple modal on website)