Framework: Relationship with JSON foreign key

Created on 16 Sep 2016  Â·  6Comments  Â·  Source: laravel/framework

Is it possible to add a feature to make relationships with JSON property as foreign key in Laravel 5.3?

class User extends Model
{
    /**
     * Get the users's preferred locale.
    /*
    public function locale()
    {
        return $this->belongsTo('App\Locale', 'preferences->locale_id', 'id');
    }
}

Most helpful comment

All 6 comments

I would strongly advise against that :)

@themsaid Is there any reason for that?

A json structure can easily get changed accidentally which will lead to unclear relationships. Anyway for such suggestions it's better that you open an issue in the internals repository rather than here.

Sent from my iPhone

On Sep 16, 2016, at 5:21 PM, hafezdivandari [email protected] wrote:

@themsaid Is there any reason for that?

—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub, or mute the thread.

Any approach on how to make that relation using the query builder?

@wa05 I haven' tried this but it may work:

$users = DB::table('users')
            ->leftJoin('locales', 'users.preferences->locale_id', '=', 'locales.id')
            ->get();

If not, try this as well:

$users = DB::table('users')
            ->join('locales', 'users.preferences->locale_id', '=', 'locales.id', 'left', true)
            ->get();
Was this page helpful?
0 / 5 - 0 ratings

Related issues

RomainSauvaire picture RomainSauvaire  Â·  3Comments

kerbylav picture kerbylav  Â·  3Comments

lzp819739483 picture lzp819739483  Â·  3Comments

iivanov2 picture iivanov2  Â·  3Comments

Anahkiasen picture Anahkiasen  Â·  3Comments