Luke Rayner
Luke Rayner

Reputation: 409

Laravel Eloquent join 2 tables together

I want to join 2 tables together using laravel eloquent. I could easily do this in mysql but have no idea using this.

I have a model called device.php this contains the following method:

public function wifi_client_connection(){
    return $this->hasMany('UserFrosting\WifiClientConnection');
}

but I need to link the WifiClientConnection.php model using a column called mac_address but WifiClientConnection doesnt have that column it has a column called device_uuid. The mac_address is converted into the device_uuid using the following method:

public function getDeviceUUID(){
    return hex2bin(md5($this->mac_address . $this->number));
}

In MySQL I join the 2 tables together like this:

LEFT OUTER JOIN device ON wifi_client_connection.device_uuid = UNHEX(MD5(CONCAT(device.mac_address, device.number)))

how can I do something like that using Laravel Eloquent.

I also need the relationship the other way round so in the WifiClientConnection.php model I have this method:

public function device(){
    return $this->belongsTo('UserFrosting\WifiClientConnection');
}

but again I would need to convert the device_uuid to mac_address for this relationship to work

Thanks for any help

Upvotes: 1

Views: 441

Answers (1)

Vince Lowe
Vince Lowe

Reputation: 3620

I would add a column with the converted value, then you can create the relationship.

public function device(){

    return $this->belongsTo('UserFrosting\WifiClientConnection', 'device_uuid', 'new_column_with_converted_value');
}

Upvotes: 0

Related Questions