[英]Convert an array to eloquent model in Laravel
I have mysql table 'test' with three columns, 我有三列的mysql表“ test”,
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? 如何将数组转换为雄辩的模型?
You could instantiate the model class with no attributes: 您可以实例化没有属性的模型类:
$dummy = new \App\Test;
Then you can call the newInstance()
method: 然后,您可以调用newInstance()
方法:
$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. 该方法中的true
标志告诉用户该实例已经存在于数据库中,因此您可以继续正常使用它。 Now you can do: 现在您可以执行以下操作:
$desiredResult->country //'1'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.