Friday, March 17, 2017

Access Eloquent's one to one relation on the WRITE connection

There is a case in my app, where I need to force the database WRITE connection when accessing a relation. How can I do it?

Models

class User extends Model
{
    /**
     * Get the phone record associated with the user.
     */
    public function phone()
    {
        return $this->hasOne('App\Phone');
    }
}

class Phone extends Model
{
    /**
     * Get the user that owns the phone.
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

Now, I've got this code:

$user = $request->user();

if ($user && $user->phone) {
    // do something...
}

Now, I need to force WRITE on this: $user->phone.

I know there's the [onWriteConnection()][1] method, however it returns a Builder object, on which I cannot use the ->phone relation.

Any idea how I can force something like this below?

// Warning: pseudo code!
if ($user && $user->onWriteConnection()->phone) {/*...*/}



via lesssugar

Advertisement