S
S
sacred12015-12-29 16:43:20
MySQL
sacred1, 2015-12-29 16:43:20

Eloquent ORM in Laravel?

There is a database, it has 2 tables (peoples, informations) connected by a foreign key (in this case it is id) there is also one data entry form. it turns out so far with only one table. Do I need to create two models for this, or register connections in the class method of our model? I would be very grateful if you could describe practically how this is implemented in laravel.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Roman Olegovich, 2015-12-29
@RusPOPsy

More or less like this

$people = People::find($id)->with('Information')->first();
$people->name = Input::get('name');
$people->Information->info = Input::get('info');
$people->save();
$people->Information->save();

S
Sergey Gladkovskiy, 2015-12-29
@SMGladkovskiy

Make data separation at the form level:

<input name="people[peoplData]" type="text">
...
<input name="information[informationData]" type="text">

In the controller (or where you implement business logic), select the appropriate arrays from the Input data (people and information) and use these arrays when creating the corresponding objects. Validation of these arrays is also easier to do in an isolated form, which I strongly advise you to do (validate) in advance and in full before creating objects, so that there are no surprises. Make a link either after creation or sequentially: create one object, add an identifier for the link to the array with data for another object and create it.
To somehow make it easier later - separate the logic for creating / changing objects into separate classes / methods so that you can transfer data there and receive in response the created objects that you will later use (or not receive if you use cqrs) .
And yes - if there are 2 tables, then these are 2 objects, under which you need to write your own models and prescribe the appropriate links in them to take into account the relationship.

R
reedwalter24, 2015-12-29
@reedwalter24

I would recommend two models, if I understand you correctly. We create two models People and Information in
the People model, write the relationship

public function informations()
    {
        return $this->belongsToMany('Information');
    }

After that we can do the following:
$people = new People();
$people->name = 'John';
if ($people->save()) {
    $info1 = new Info();
    $info->title = 'info1';
    $info1->save();
    
    $info2 = new Info();
    $info->title = 'info2';
    $info2->save();

    $people->informations()->sync(array(info1->id, info2->id));
}

I described the idea, I can’t check the performance at the moment :)
Read about sync

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question