How to merge the return from one to one relationship - laravel

I am using one to one relationship in laravel.
I have two models one is User and another is UserDetails.
The relationship is in User model
public function userDetails(){
return $this->hasOne(UserDetail::class);
}
I am calling the models something like that
public function index()
{
$user = User::find(2);
$user->user_details = $user->userDetails;
echo "<pre>"; print_r($user->toArray()); die;
}
But I am printing the return getting like this:-
Array
(
[id] => 2
[name] => Joney
[email] => joney#gmail.com
[email_verified_at] => 2019-04-29 02:01:03
[password] => dasDSADASDASDAS
[status] => Active
[remember_token] => DSADASd
[created_at] => 2019-04-29 00:00:00
[updated_at] => 2018-09-24 02:00:00
[user_details] => Array
(
[id] => 2
[user_id] => 2
[address] => Dhampur
[mobile_number] => 8006009195
[passport_number] => sasdadasd
[zip_code] => 201301
[created_at] => 2019-04-29 06:00:00
[updated_at] => 2019-04-29 02:00:00
)
)
So I want to get the return after merge the details into an object.
Thanks

try below code:
$user = User::with('userDetails')->find(2);
$user->user_detail_id = $user->userDetails->id;
$user->address = $user->userDetails->address;
$user->mobile_number = $user->userDetails->mobile_number;
$user->passport_number = $user->userDetails->passport_number;
$user->zip_code = $user->userDetails->zip_code;
unset($user->userDetails);
echo "<pre>"; print_r($user->toArray()); die;
Thanks.

This will happen automatically when you load the relationship. You can do this with either with() or load() depending on whether you have the model or not.
With your example above you would use with() as you're getting the user at the same time:
$user = User::with('userDetails')->find(2);
Alternatively, if you already had the User model then you would use load():
$user = User::find(2);
$user->load('userDetails');
Now, with all of that said, since you only have the one User model and not a collection, you don't need to worry about the (n+1) problem that eager loading solves so you can just access the property and Laravel will automatically getthe information for you e.g.:
$user = User::find(2);
$user->user_details;
Now if you do dd($user->toArray()) you will see that the information has been loaded.
Just an FYI, instead of using print_r() with die() and wrapping it in <pre> tags, you can use the dump() and dd() helper functions instead.

Have you try this
$user = User::find(2)
echo print-r ($user->userDetails);

Related

Laravel Eloquent ORM relationship query

I need help, I have a problem with querying Model Relationships.
I actually know and get the job done using the query method but I'd like to know the "laravel way" of querying relationships.
Here's what's on my controller.
//HealthProfile Controller
//$id value is 2
$health_profiles = User::find($id)->with('health_profiles')->first();
problem is that the return for the query is the records for id = 1 and not id = 2. It basically ignored the "find" method. I just want to get the health profiles for a specific user_id.
[id] => 1
[firstname] => patrick
[lastname] => marino
[email] => patrick#gmail.com
[membership_code] => starpatrick
[birthdate] => 1989-05-17
[contact_number] => 1230123
[active] => 1
[created_at] => 2014-07-01 16:10:05
[updated_at] => 2014-07-01 16:10:05
[remember_token] =>
[health_profiles] => Array
(
[0] => Array
(
[id] => 1
[user_id] => 1
[parent_id] =>
[name] => patrick star
[relationship] =>
[gender] => male
[birthdate] => 1989-05-17
[marital_status] =>
[number_of_children] =>
[weigth] =>
[height] =>
[blood_type] =>
[blood_pressure] =>
[hdl] =>
[ldl] =>
[vldl] =>
[visual_activity] =>
[lifestyle] =>
[current_bmi] =>
[weight_goal] =>
[weekly_goal] =>
[rdc] =>
[created_at] => 2014-07-01 16:10:05
[updated_at] => 2014-07-01 16:10:05
)
This is my schema
//User model
public function health_profiles()
{
return $this->hasMany('HealthProfile');
}
//HealthProfile model
public function user()
{
return $this->belongsTo('User', 'user_id', 'id');
}
First a few words of explanation:
find($id) already runs the query (it uses where(id, $id)->first() under the hood) so place it at the end, because now you unwittingly did this:
User::find($id);
User::with('health_profiles')->first();
Another problem is, like you already noticed, that Eloquent won't work with this setup:
public function health_profiles() ...
$user = User::find($id);
$user->health_profiles; // null
because when loading dynamic properties (relations) it looks for camelCased method on the model.
However eager loading will work as expected:
$user = User::with('health_profiles')->find($id);
$user->health_profiles; // related model/collection
So you definitely should comply with the naming conventions if you want Eloquent to be your friend ;)
But that's not all. It will work the other way around:
public function healthProfiles() ...
$user = User::find($id);
$user->healthProfiles; // works, returns related model/collection
$user->health_profiles; // works as well, returns the model/collection
To sum up and answer your question, each of those will work for you:
// Assuming Profile is the model
// 2 queries
$user = User::find($id);
$profiles = $user->healthProfiles;
// or 1 query
$profiles = Profile::where('user_id', $id)->get();
// or 2 queries: 1 + 1 subquery
$profiles = Profile::whereHas('user', function ($q) use ($id) {
$q->where('users.id', $id);
})->get();
You can try putting the with before the find so that the builder knows to eager load that relationship on what you are trying to find.
$user = User::with('health_profiles')->find($user_id);
$health_profiles = $user->health_profiles;
Try this
User::with('health_profiles')->find($id);
I don't think you need to call the first method because find as it's stated will only find the one row of data that you need.
I've found the culprit. L4 has problems with snake cased methods! I changed it to camelCase and it worked.
$lawly = User::where('id', '=', 2)->first();
$lawly->healthProfiles->toArray()
src: https://coderwall.com/p/xjomzg

sorting and filtering not working in custom admin module

I am trying to implement an admin module in magento which has a grid in the first page and grids in the tabs while editing the grid entities.
The main grid works fine, but the grids in the tabs are not working fine.
The problem I found while I debugged the code is that, I am loading the collection in the grid with field filtering, ie I am filtering the collection with filter that is the user id. I did this because I need only data of a single user from the table. This made the entire problem, the data in the grid is coming correctly, but the filtering,sorting and searching feature inside grid is not working and returning a 404 not found error page. I tried removing the field filter I added while getting the collection, then it works fine but all the data in the table is coming which is the opposite to my requirement.
Is there any possible solution to this. Here is the way I am trying to do:
protected function _prepareCollection() {
$collection = Mage::getModel('merchant/subscriptions')->getCollection()->addFieldToFilter('user_id', Mage::registry('merchant_data')->getId());
$this->setCollection($collection); //Set the collection
return parent::_prepareCollection();
}
Thanks in advance.
ok My problem is solved there is a mistake in my code. In the grid file the function below was wrong.
public function getGridUrl() {
return $this->getUrl('*/*/transactiongrid', array('user_id',Mage::registry('merchant_data')->getId(), '_current' => true));
}
The correct method was
public function getGridUrl() {
return $this->getUrl('*/*/transactiongrid', array('user_id'=> Mage::registry('merchant_data')->getId(), '_current' => true));
}
Filter action is dependent on your below method:
public function getGridUrl() {
return $this->getUrl('*/*/grid', array('user_id' => Mage::registry('merchant_data')->getId(),'_current'=>true));
}
now this is how you will prepare collection:
protected function _prepareCollection()
{
$regData = Mage::registry('merchant_data');
if(isset($regData))
$regData = $regData->getId();
else
$regData = $this->getRequest()->getParam('user_id');
$collection = Mage::getModel('merchant/subscriptions')->getCollection()->addFieldToFilter('user_id',$regData);
...
When I dumped $regData I got this:
Cubet_Merchant_Model_Merchant Object
(
[_eventPrefix:protected] => core_abstract
[_eventObject:protected] => object
[_resourceName:protected] => merchant/merchant
[_resource:protected] =>
[_resourceCollectionName:protected] => merchant/merchant_collection
[_cacheTag:protected] =>
[_dataSaveAllowed:protected] => 1
[_isObjectNew:protected] =>
[_data:protected] => Array
(
[user_id] => 3
[firstname] => Robin
[lastname] => Cubet
[email] => robin#cubettech.com
[username] => robincubet
[password] => 51a7f45eb11fc49b5967a0039193c3ad:HSX8JkSO5lr3uaRHrzd86i7gb0RATeDb
[created] => 2013-12-12 08:34:28
[modified] => 2013-12-16 09:03:56
[logdate] =>
[lognum] => 0
[reload_acl_flag] => 1
[is_active] => 1
[extra] => N;
[rp_token] =>
[rp_token_created_at] =>
)
[_hasDataChanges:protected] =>
[_origData:protected] => Array
(
[user_id] => 3
[firstname] => Robin
[lastname] => Cubet
[email] => robin#cubettech.com
[username] => robincubet
[password] => 51a7f45eb11fc49b5967a0039193c3ad:HSX8JkSO5lr3uaRHrzd86i7gb0RATeDb
[created] => 2013-12-12 08:34:28
[modified] => 2013-12-16 09:03:56
[logdate] =>
[lognum] => 0
[reload_acl_flag] => 1
[is_active] => 1
[extra] => N;
[rp_token] =>
[rp_token_created_at] =>
)
[_idFieldName:protected] => user_id
[_isDeleted:protected] =>
[_oldFieldsMap:protected] => Array
(
)
[_syncFieldsMap:protected] => Array
(
)
)

codeignite trying to get property of non-object not resolved

I am attempting to access the result set from a model query in the view. I have the following:
Controller:
$courseId = $this->session->userdata('courseId');
//echo "Course: ".$courseId;
if(isset($courseId) && $courseId != '')
{
$result = $this->Course_model->loadBasicDetailsEdit($courseId);
$data['basicCourseDetails'] = $result;
$this->load->view('course/basicDetails', $data);
}
Model:
function loadBasicDetailsEdit($courseId)
{
$this->db->select('*');
$this->db->where('course_id', $courseId);
$this->db->from('course');
$query = $this->db->get();
if ( $query->num_rows() > 0 )
{
return $query->result();
} else {
return FALSE;
}
}
and in the view I tried to print_r() and got this:
Array ( [0] => stdClass Object ( [course_id] => 8 [title] => Photography [summary] => [description] => [price] => [member_id] => 12 [category] => [audience] => [goals] => [date] => 2013-09-26 [production] => 0 ) )
I tried to access this using $basicCourseDetails->title or $basicCourseDetails['title']
but neither are working. Any hint as to why this is happening?
Regards,
try this:
foreach($basicCourseDetails as $basic){
echo($basic->title);
}
or something like this:
echo($basicCourseDetails[0]->title);
This is an array of objects
Array ( [0] => stdClass Object ( [course_id] => 8 [title] => Photography [summary] => [description] => [price] => [member_id] => 12 [category] => [audience] => [goals] => [date] => 2013-09-26 [production] => 0 ) )
Contains one stdObject in the array, so, first objects is 0, if there were more, then second item could have index 1 and so on. To retrieve data from the first (here is only one) stdobject you may use
echo $basicCourseDetails[0]->title; // title will be printed
You can send data to the view page by this line of code which is mentioned in above question.
$result = $this->Course_model->loadBasicDetailsEdit($courseId);
$data['basicCourseDetails'] = $result;
$this->load->view('course/basicDetails', $data);
But when you will access these data in view then you need to access all data one by one by using foreachloop in the view page.
For example if you have a view page like basic_details.php inside course folder then you need to write code like this to access these data.
foreach ($basicCourseDetails as $key => $value) {
$name = $value->name;
}
The above foreachloop can be written in view page where you want to access data.

Symfony Unset Attribute

I have the following session data from symfony2
[attributes:protected] => Array
(
[_security_secured_area] =>
[ids] => Array
(
[0] => 1426
[1] => 1427
[2] => 1428
)
)
I want to remove the ids 1428. I have read about $session->remove but want to, how to use it for multi-d array ...
The session class is just a store for the data. So you have to handle this on your own:
$ids = $session->get('ids');
$ids = someFunctionToUnsetTheId($ids, $idToRemove);
$session->set('ids', $ids);
If you have some more information about the IDs, you could look into namespacing the session keys:
$tokens = $session->get('tokens');
$tokens['c'] = $value;
$session->set('tokens', $tokens);
$session->set('tokens/c', $value);
Code example taken from the Symfony doc.

Use Array Data in CodeIgniter Model as SQL?

In my controller, I am passing data to the model using the following code:
$data = array(
'gid' => $this->input->post('gid'),
'name' => $this->input->post('name'),
'pic' => $this->input->post('pic'),
'link' => $this->input->post('link')
);
var_dump($data);
$this->Login_model->insert_entry($data);
In my model, what I want to do is use the gid value as part of an SQL statement, like so:
$get_gid = $this->db->query('SELECT * FROM users WHERE gid = $gid');
Obviously this doesn't work, so I'm just wondering how I get the gid from $data and use it in my SQL statement?
Tested using
$get_gid = $this->db->where('gid', $data['gid'])->get('users');
print_r($get_gid);
However output is:
CI_DB_mysql_result Object ( [conn_id] => Resource id #30 [result_id]
=> Resource id #33 [result_array] => Array ( ) [result_object] => Array ( ) [custom_result_object] => Array ( ) [current_row] => 0
[num_rows] => 0 [row_data] => )
Did you try gid = $data['gid']
I assume that yours model method looks like this:
insert_entry($data)
{
here active record or query...
}
If yes try to display query to see if $data['gid'] is visible there
You can try it by
$this->db->get_compiled_select();
Or after query runs
$this->db->last_query();
Try this way:
$data = array(
'gid' => $this->input->post('gid'),
'name' => $this->input->post('name'),
'pic' => $this->input->post('pic'),
'link' => $this->input->post('link')
);
$gid = $data['gid'];
$this->db->where('gid',$gid);
$this->db->from('users');
$query = $this->db->get();
if($query)
{
//you can return query or you can do other operations here like insert the array data
//$this->db->insert('yourtable',$data);
return $query;
}
else
{
return FALSE;
}
You can try:
$get_gid = $this->db->query('SELECT * FROM users WHERE gid = '.$data['gid'].');
You just Forget after query $query->result().

Resources