logo
down
shadow

3 tables many to many relationship


3 tables many to many relationship

Content Index :

3 tables many to many relationship
Tag : php , By : ravibits
Date : November 26 2020, 12:01 PM

I wish this helpful for you Until more details are provided, I'm assuming the relationships are as follows:
User model and JobOffer model have an M:N relationship Company model and JobOffer model have a 1:M relationship
# App\User.php
public function job_offers()
{
    return $this->belongsToMany('App\JobOffer')->withTimestamps();
}
# App\JobOffer.php
public function users()
{
    return $this->belongsToMany('App\User')->withTimestamps();
}

public function company()
{
    return $this->belongsTo('App\Company');
}
# App\Company.php
public function job_offers()
{
    return $this->hasMany('App\JobOffer');
}
use App\User;

$user = User::with('job_offers.company')->where(...)->first();
App\User {
  id: 1,
  created_at: "",
  updated_at: "",
  job_offers: Illuminate\Database\Eloquent\Collection {
    all: [
      App\JobOffer {
        id: 85,
        company_id: 36,
        created_at: "",
        updated_at: "",
        pivot: Illuminate\Database\Eloquent\Relations\Pivot {
          job_offer_id: 85,
          user_id: 1,
          created_at: "",
          updated_at: "",
        },
        company: App\Company {
          id: 36,
          name: "Company1"
          created_at: "",
          updated_at: "",
        },
      },
      App\JobOffer {
        id: 90,
        company_id: 44,
        created_at: "",
        updated_at: "",
        pivot: Illuminate\Database\Eloquent\Relations\Pivot {
          job_offer_id: 90,
          user_id: 1,
          created_at: "",
          updated_at: "",
        },
        company: App\Company {
          id: 44,
          name: "Company2"
          created_at: "",
          updated_at: "",
        },
      },
    ],
  },
}
@foreach($user->job_offers as $job_offer)
    Company name: {{ $job_offer->company->name }}
@endforeach

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Creating a one-to-one relationship between tables with an existing one-to-many relationship


Tag : sql , By : Epora75
Date : March 29 2020, 07:55 AM
Hope that helps There is nothing (in my opinion) wrong with your initial thought.
Although there is a loop as you put it, there isn't a problem here.

Duplicate tables having N:M relationship (including relationship)


Tag : php , By : OlioEngr
Date : March 29 2020, 07:55 AM
like below fixes the issue You say you can't change the table structure. If you could, I would likely recommend against the denormalization (duplication of rows) of these tables depending upon what you are doing.
I'm also a bit confused because you say you have to duplicate the rows and relations with id_category = 1 to id_category = 3, but then your sample queries have id_category = 2.
$pdo = new PDO('mysql:host=?', $user, $passwd);
$stmtCustomers = $pdo->prepare("INSERT INTO customer (t_name, id_category)
   VALUES (t_name, ?) WHERE id_category = ?");
$stmtContracts = $pdo->prepare("INSERT INTO contract (t_name, id_category)
   VALUES (t_name, ?) WHERE id_category = ?");
$stmtRelation = $pdo->prepare("INSERT INTO customer_has_contract VALUES (?, ?)");

//Perform in a loop if needed
$pdo->beginTransaction();
$stmtCustomers->execute($target_cat_id, $origin_cat_id);
$cus_id = $pdo->lastInsertId();
$stmtContracts->execute($target_cat_id, $origin_cat_id);
$con_id = $pdo->lastInsertId();
$stmtRelation->execute($con_id, $cus_id);
$pdo->commit();

Entity Relationship Diagram. How does the IS A relationship translate into tables?


Tag : development , By : Pip
Date : March 29 2020, 07:55 AM
Hope that helps Assuming the relationship is mandatory (as you said, a person has to be a student or a teacher) and disjoint (a person is either a student or a teacher, but not both), the best solution is with 2 tables, one for students and one for teachers.
If the participation is instead optional (which is not your case, but let's put it for completeness), then the 3 tables option is the way to go, with a Person(PersonID, Name) table and then the two other tables which will reference the Person table, e.g. Student(PersonID, GPA), with PersonID being PK and FK referencing Person(PersonID).

How can we identify the relationship between two SQL Server tables , either one to one or some other relationship.....?


Tag : sql , By : redha
Date : March 29 2020, 07:55 AM
around this issue In SQL Server, create a new view in your database, add the two tables you want to see the relationship with.

How do I create a relationship between two tables where one already has a relationship with another table?


Tag : sql-server , By : Nic Doye
Date : March 29 2020, 07:55 AM
it should still fix some issue The reason is your Courses table has 2 field in it's primary key. On solution is you add a new field named semesterId in Enrollment table and use both semesterId and courseId when creating foreign key.
Related Posts Related QUESTIONS :
  • How to login/logout with Hybridauth 3?
  • Convert INT number in PHP
  • php/mysql. selecting 2 common fields in 2 tables
  • Expand an string based on values in an array in PHP
  • When you absolutely have to manually escape SQL in CakePHP 3.4.7
  • Htaccess redirecting wrong page
  • Laravel Optional WHERE clause
  • PHP unpack overlfow variable memory limit
  • How to check the URL's structure using PHP preg_match?
  • PHP preg_replace - text will not be recognized
  • Show image from other domain without showing the domain name - PHP
  • How to run and watch local server at the same time?
  • Access form request from Observer laravel
  • single quote problem with preg_replace_callback
  • How to Create A Unique URL for each product enquiry form for Google Analytics Tracking
  • Laravel email configuration: what am I missing?
  • Assign indexed array values to multidimensional array?
  • Custom WordPress stylesheet not loading
  • Data attribute only returning first value
  • How to list all roles with Permissions,in spatie permission Package?
  • How to achieve this number pattern with n input
  • How to iterate array inside array data in laravel ,output are given below
  • To get output of movie with its genre
  • Extracting some data from a JS object literal string in PHP using Regex
  • axios and vuex are deleting wrong index in array
  • Setting empty CURLOPT_POSTFIELDS
  • Laravel 5.8 use subdomain as API endpoint beside domain.com/api
  • Error while add data in database SQL Server 2016
  • Does PhpStorm allow to skip PHPDoc tags when type hints is declared?
  • html classes are changed to Attributes
  • Using json to import multidimensional data
  • passing data from the view to the controller, where the data comes from another controller
  • How to extract integer and decimal numbers in PHP string correctly?
  • Parsing Sub-Object from an XML Feed with objects
  • Getting error "Unknown column 'text' in 'field list'"
  • How to properly get onedrive access token via php and curl
  • How to add spell check to a php function
  • Is it posible to create css rules with php?
  • Pretty URL with $_GET method
  • Wordpress always load same page - index.php
  • Find value in array and return with new from different array
  • PHP multiple file upload with different keys
  • Can't modify times one a time without weird errors
  • Get size of scraped image with domcrawler (Goutte)
  • Laravel - Ordering a collection of models
  • PHP Fatal error: Uncaught Error: Call to a member function setFetchMode() on boolean
  • Strict Standards: Only variables should be passed by reference in /main_dir/sub_dir/backup.php
  • Uncaught Google_Exception: (update) unknown parameter: 'copyRequiresWriterPermission'
  • Laravel 5 form does not redirect with old input
  • How to get values greater than or equal to in Mysql database sql when its a value like 1:00 PM?
  • PHP datediff overday issue
  • Masking an auto incrementing primary key
  • How to grab a String BEFORE a certain word
  • ZF2 Routing Multiple Controllers based on route constraints
  • How to deregister/dequeue jquery.sticky.js in Elementor (Pro)?
  • How to fix errors counting words in text plain with PHP?
  • How to get View data in Laravel in custom helper or directive
  • Creating a new data entry into a database with eloquent and trying to access the variable in the url
  • How to test authentication using Laravel Dusk?
  • PHP parse_str not getting all $_GET variables
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com