Laravel model without db

I have a Meal model that can contain an Ingredient model and Ingredient has many properties ...

I have all the ingredients in the DB, as well as some dishes ....

But I want to create a new food, but without storing it in the database.

so something like:

$meal = new Meal; $meal->ingredients()->attach(5); 

where 5 is the identifier of the ingredient in the database.

However, this will not work, because $ food is not stored in the DB and the attach () function is trying to create a new entry in the meal_ingredient table ....

So, is there a way to create an "autonomous" model and connect it to the "online" data?

thanks

+6
source share
2 answers

Your question:

So, is there a way to create an โ€œautonomousโ€ model and link it to โ€œonlineโ€ data?


Our choice:

  • Yes, you can use a kind of Laravel Model without a database (offline, as you express it). See jenssegers / laravel-model . Basically this is a class that implements ArrayAccess , ArrayableInterface , JsonableInterface with some states and behavior as needed.

  • Yes, there must be a way to connect the Illuminate\Database\Eloquent\Model Online to your "stand-alone" model: POO and Design Pattern are on their way to salvation. Hold your hands, feel free to delve into the source code!

We suggest that you flip your own "stand-alone" model based on the jenssegers/laravel-model source code and expand the "Online" Illuminate\Database\Eloquent\Model (Decorator template or something else !?) so that he knows about the first. Plumbing remains with you, not a single false power code so far ;-)


Notes:

You may have to define some user-specific dependent (helper) classes of Illuminate\Database\Eloquent\Model , such as Illuminate\Database\Eloquent\Relations\BelongsToMany , etc.

FIY, you can also find the corresponding Illuminate\Database\Eloquent\Model extension example here jarektkaczyk / Eloquent-triple-pivot using the latest PHP features.

Happy coding.

+5
source

You should consider the object as a collection to work "offline". And do not forget to build objects that they do not exist.

 $ingredient = new Ingredient; $ingredient->id = 5; $meal = new Meal; $meal->ingredients->add($ingredient); 

Thus, neither food nor ingredient number 5 should exist in the database.

+4
source

Source: https://habr.com/ru/post/971768/


All Articles