CREATE TABLE companies
(
id int NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE customers
(
id int NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
companies_id int NOT NULL,
PRIMARY KEY (id),
CONSTRAINT companies_id_fk FOREIGN KEY (companies_id)
REFERENCES companies(id)
);
[Insert table script]
INSERT INTO companies (name) VALUES ('a company');
INSERT INTO customers (name, companies_id) VALUES ('a customer', 1);
[Model]
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
protected $table = 'customers';
public function company()
{
return $this->belongsTo(Company::class, 'companies_id');
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
protected $table = 'companies';
public function customer()
{
return $this->hasOne(Customer::class, 'companies_id');
}
}
[Controller]
$customer = Customer::with(['company'])->get();
select * from customersselect * from companies where companies.id in (1)
[
{
"id": 1,
"name": "a customer",
"companies_id": 1,
"company": {
"id": 1,
"name": "a company"
}
}
]
$companies = Company::with(['customer'])->get();
select * from companiesselect * from customers where customers.companies_id in (1)
[
{
"id": 1,
"name": "a company",
"customer": {
"id": 2,
"name": "a customer",
"companies_id": 1
}
}
]
INSERT INTO companies (name) VALUES ('a company');
INSERT INTO customers (name, companies_id) VALUES ('a customer', 1);
$customer = Customer::with(['company'])->get();
select * from customers
select * from companies where companies.id in (1)
$companies = Company::with(['customer'])->get();
select * from companies
select * from customers where customers.companies_id in (1)