#eloquent

1 messages · Page 1 of 1 (latest)

ebon vapor
#

How to make a eloquent relation based on custom foreign key?

public function member()
{
return $this->hasOne(Member::class, DB::raw('CONCAT(first, " ", last)'), 'name');
}

query output is which is not correct

SELECT
*
FROM
members
WHERE
members.CONCAT(first, " ", last) = "Andrew"
AND members.CONCAT(first_name, " ", last_name) IS NOT NULL
AND members.deleted_at IS NULL
limit
1

I want to use CONCAT(first, " ", last) as a foreign key

lavish jolt
#

why? you should use the primary key instead.

#

also, raw query is not going to work at this case if you are using eloquent.

ebon vapor
#

I want a relation where member first_name last_name matches the name

#

Don't have any relation between these two tables.

lavish jolt
#

primary key?

#

column id?

#

you known there are a lot of people have the same name as me, how are you going to tell they are different users?

ebon vapor
#

Yes, there could be many users with the same name, but I just want to pick up the first one.

#

which matched the condition

lavish jolt
#

sigh

#

fine. don't use the eloquent's relationship, call a new query instead

$user = User::query()->where('condition matache')->first();
$member = Member::query()->whereRaw('concat(first_name," " last_name) = ? ',[$user->name])->first();
ebon vapor
#

This I know, I just wanted to use it as a relation so I can take advantage of Laravel's Eggloading

lavish jolt
#

and i'm out