6
6
655362016-10-08 01:35:20
Laravel
65536, 2016-10-08 01:35:20

Linking models with link type morphTo?

There are two models...

class BalanceOperation extends \Model
{
    protected $table = 'gc_balance_operations';

    public function contractor()
    {
        return $this->morphTo();
    }

    ...
}

class Client extends \Model
{
    protected $table = 'gc_clients';

    public function balanceOperations()
    {
        return $this->morphMany(BalanceOperation::class, 'contractor');
    }

    ...
}

Is there any way to link two existing models with one hand movement. I didn't find it and link like this:
$operation->contractor_type = get_class($contractor);
$operation->contractor_id = $contractor->id;

$operation->save();

I tried methods for other types of communication (save, attach, associate) - none of them work either on the model or on the builder. And there is nothing in the documentation about this, only about selections. It is reluctant to get into the eloquent. Tell me who knows for sure whether this feature exists or not

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Victor, 2016-10-08
@65536

Должно работать так, при условии, что связь правильно настроена.

$operation->contractor()->associate($contractor);
$operation->save();

associate не сохраняет модель, только задает нужные атрибуты.
Зря не хотите заходить в исходники, по ним почти всегда можно понять, как работает метод.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question