t0berius
2 years ago

Join two tables

Posted 2 years ago by t0berius

I'm searching for an elegant way to get the query below done, without using laravel Database query builder, instead I would like to use eloquent.

The query in "plain" SQL:

$addresses = SELECT * FROM addresses, linked_addresses WHERE addresses.address = linked_addresses.address WHERE code != 5;

The models:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;

class LinkedAddress extends Model
{
    public static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            $model->created_at = Carbon::now();
        });
    }

    protected $table = 'linked_addresses';
    protected $primaryKey = ['code', 'address'];
    public $timestamps = false;
    public $incrementing = false;

    protected $fillable = [
        'code',
        'address',
    ];
    
    protected $dates = [
         'created_at',
    ];

    public function address()
    {
        return $this->belongsTo('App\Address', 'address', 'address');
    }

}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Address extends Model
{
    protected $table = 'addresses';

    protected $fillable = [
        'address',
        'balance',
    ];

    public function linked_addresses()
    {
        return $this->hasMany('App\LinkedAddress', 'address', 'address');
    }
}

Please sign in or create an account to participate in this conversation.