2020-04-01 12:35:06 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Enables a pushnew() method, similar to push() but when all relationships are new records
|
|
|
|
*
|
|
|
|
* Base on Model::push()
|
|
|
|
*/
|
|
|
|
namespace App\Traits;
|
|
|
|
|
|
|
|
use Illuminate\Database\Eloquent\Collection;
|
2024-08-03 00:06:25 +00:00
|
|
|
use Illuminate\Support\Facades\Log;
|
2020-04-01 12:35:06 +00:00
|
|
|
|
|
|
|
trait PushNew
|
|
|
|
{
|
|
|
|
public function pushNew() {
|
|
|
|
if (! $this->save()) {
|
2020-07-06 06:02:59 +00:00
|
|
|
// We dont traverse this models relations
|
2020-04-01 12:35:06 +00:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
// To sync all of the relationships to the database, we will simply spin through
|
|
|
|
// the relationships and save each model via this "pushNew" method, which allows
|
|
|
|
// us to recurse into all of these nested relations for the model instance.
|
2020-07-06 06:02:59 +00:00
|
|
|
foreach ($this->relations as $key => $models) {
|
|
|
|
// If we are not pushable, jump to the next item.
|
2024-08-03 00:06:25 +00:00
|
|
|
if ((! is_array($this->pushable)) || (! in_array($key,$this->pushable)))
|
2020-07-06 06:02:59 +00:00
|
|
|
continue;
|
|
|
|
|
2020-04-01 12:35:06 +00:00
|
|
|
$models = $models instanceof Collection
|
|
|
|
? $models->all() : [$models];
|
|
|
|
|
|
|
|
foreach (array_filter($models) as $model) {
|
|
|
|
$model->setAttribute($this->getForeignKey(),$this->{$this->getKeyName()});
|
|
|
|
|
|
|
|
if (! $model->pushNew()) {
|
2024-08-03 00:06:25 +00:00
|
|
|
Log::alert('Failed to save model',['attrs'=>$model->getAttributes()]);
|
|
|
|
|
2020-04-01 12:35:06 +00:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|