E
E
EVOSandru62019-12-22 00:25:53
Laravel
EVOSandru6, 2019-12-22 00:25:53

How to combine 2 expressions in Eloquent into one - creating a model and getting its context along with each statement?

Good afternoon.
Thus, I create and get the context of the created model in $attribute
$attribute = factory(Attribute::class)->create();
Next, I create communication models, everything is ok:

$attribute->multiples()->createMany(factory(Multiple::class, $multiples_count)->raw());

But if I combine 2 expressions into one:
$attribute = factory(Attribute::class)->create()->each(function (Attribute $createdAttribute) {
     $createdAttribute->multiples()->createMany(factory(Multiple::class, $multiples_count)->raw());
});

Then $attribure does not contain the context of the created model. How can you make it contained?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Sokharev, 2019-12-23
@greabock

factory(Attribute::class)->create();
As far as I can understand, it will return an instance of the Attribute model. But then you chain. A logical question arises each (each), sorry, what ? But even let's say that you have a typo, and you wanted to write
But then it's right
And in $attributes there will be a collection of Attribute instances.
Let's move on ... let's say we corrected this matter and wrote it correctly

$attributes = factory(Attribute::class, 2)->create()->each(function (Attribute $createdAttribute) {
     $createdAttribute->multiples()->createMany(factory(Multiple::class, $multiples_count)->raw());
});

Where does $multiples_count come from in the clojure?
well let's fix that
$multiples_count = 5;
$attributes = factory(Attribute::class, 2)->create()->each(function (Attribute $createdAttribute) use ($multiples_count) {
     $createdAttribute->multiples()->createMany(factory(Multiple::class, $multiples_count)->raw());
});

Then
$multiples_count = 5;
$attributes = factory(Attribute::class, 2)->create()->each(function (Attribute $createdAttribute) use ($multiples_count) {
     $createdAttribute->multiples()->createMany(factory(Multiple::class, $multiples_count)->raw());
});

foreach  ($attributes as $attribute) {
   $attribute->doSomeThing(); // Вот вам и ваш "контекст"
}

By the way, "context" - the term, in this case, inappropriate. Instance/Object/Instance are the right words.
"Context" is about $this/static/self pointers or the current scope. What exactly - depends on the context of the conversation, sorry for the pun)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question