Reputation: 147
I have mysql table 'test' with three columns,
1.sno 2.name 4.country
this code is easily understandable
$person = \App\Test::find(1);
$person->country; //Defined in Test eloquent model
now i want to do something like this:
$p = ['sno' => 1, 'name' => 'Joe', 'country' => '1' ];
$p->country; //Return relevent column form countries table as defined in Model
The thing to remember is that the user i am trying to map is already present in the database table. How to i convert an array to eloquent model?
Upvotes: 1
Views: 5708
Reputation: 56
You could instantiate the model class with no attributes:
$dummy = new \App\Test;
Then you can call the newInstance()
method:
$attributes = ['sno' => 1, 'name' => 'Joe', 'country' => '1' ];
$desiredResult = $dummy->newInstance($attributes, true);
The true
flag in the method is telling eloquent that the instance already exists in database, so you can continue working with it normally. Now you can do:
$desiredResult->country //'1'
Upvotes: 4