thanaponlp57 / lumen-relationship

0 stars 0 forks source link

One to One #1

Open thanaponlp57 opened 1 year ago

thanaponlp57 commented 1 year ago

[Create table script]

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 customers select * 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 companies select * from customers where customers.companies_id in (1)

[
    {
        "id": 1,
        "name": "a company",
        "customer": {
            "id": 2,
            "name": "a customer",
            "companies_id": 1
        }
    }
]
thanaponlp57 commented 1 year ago

TIP:

Passfunction callback and call select statement

$customers = Customer::with(
    [
        'customer' => function ($query) {
            $query->select(['id', 'name', 'companies_id']);
        }
    ]
);