dimanche 13 octobre 2019

Eloquent Builder Macro, get the relationship id

I'm trying to add a macro for my query builder so I could have something like this

$person = Person::first();
$person->activity()->log("Newest Activity");

Unfortunately my implementation generates an error

General error: 1364 Field 'person_id' doesn't have a default value

Here is my Implementation,I have a 2 class model,

one is Person Model

public class Person extends Model {

    public function activity()
    {
        return $this->hasMany(Activity::class, "person_id");
    }

}

and ActivityLog Model

public class ActivityLog extends Model {

    public function newEloquentBuilder($query)
    {
        $builder = parent::newEloquentBuilder($query);

        $builder->macro('log', function (Builder $builder, $value) use ($query) {  
            return  $builder->getModel()
                ->newInstance([
                   'person_id' => // How to get the id from relationship
                   'details' => $value
                ])
                ->save();
        });

        return $builder;
    }
}

I know how to do it in laravels way, but I want to avoid specifying keys, this is one of the reason why I am doing this.

How do I access the value of it person_id from the relationship, so that my implementation work?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2nLBWXI
via IFTTT

Aucun commentaire:

Enregistrer un commentaire