get one row of dummy data with eloquent - laravel

Take this example
$result = Players::select("first_name", "last_name")->where("some_field", "some_value");
That returns a Illuminate\Database\Eloquent\Builder
Now I would like to "simulate" that same thing but with dummy data, so I did this
$result = Players::select(DB::raw("'john', 'doe'"));
That works, but when the query runs, if the the players table has 10 rows I get 10 rows filled with john doe and I only need just one.
I've tried doing
$result = Players::select(DB::raw("'john', 'doe'"))->limit(1);
but that has no effect
How can I get only 1 row of dummy data? Taking into account that $result must return a Illuminate\Database\Eloquent\Builder

if you want to do it in your suggested way i think this should work :
$result = Players::select(DB::raw("'john' as first_name , 'doe' as last_name"))->take(1);

Related

Problem trying to insert a value from a query with eloquent

i'm trying to select and insert values into a database with eloquent models. The thing is, i made a query to get a value from another table and insert it in the new one. But it keeps inserting 0 when it should insert the value of the id that i'm retrieving
This is the way i'm selecting the id from table clients:
$client_id = Client::select('id')->where('dni', '=', $request->client)->first();
\Log::debug($client_id);
The debug on the Log returns this:
[2020-08-05 17:43:25] local.DEBUG: {"id":1}
And this is the insert:
$seguro = new Seguro();
$seguro->usuario_id = $user_id;
$seguro->cliente_id = $client_id;
$seguro->save();
And the insert is successfull except for the column cliente_id where i'm getting 0 instead of 1.
Can anyone help me with this?
Your $client_id contains object (model), not integer value. You can even see this in debug. Just get id from this model using ->id
$seguro->cliente_id = $client_id->id; // also better change name $client_id to $client
or
$client_id = Client::select('id')->where('dni', '=', $request->client)->first()->id;
Also it is good idea to write code in english (variable names). For example I do not know what "dni" should mean in this query.

How can I get specific column fields?

I want return specific columns for every card that is returned by eloquent relationship.
I can do it with ->get(['column1', 'column2']) but in this situation I can't use get().
Is there a solution for this ?
$deckId = $request->deckId;
$deck = Deck::find($deckId);
return $deck->cards;
on the cards I want for example just the id the name and the card_type
This code should work if you already defined the relationship
return $deck->cards()->get(['id', 'name', 'card_type']);
Have you looked into pluck?
Deck::all()->pluck('column1', 'column2');
This will return an array with column1 as key and column2 as value

Join query in laravel with data manipulation send to view

I am having 2 tables, users and profiledetails
I am able to run Join query and access the data and send to view.
But when I am manipulation the field 'dob' (date format) in profiledetails table. No Success, Please check the code below ,
webpagesConroller:
$users = DB::table('users')
->join('profiledetails', 'users.id', '=', 'profiledetails.user_id')
->select('users.*', 'profiledetails.dob')
->get();
$age = $users->dob->diffInYears(Carbon::now());
return view('webpages.index',compact('users'))->with($age);
View:
<li class="cate_head">Age : {{ $age}}</li>
Error:
Trying to get property of non-object
I have model Profiledetails added the mutators as below,
public function getAge(){
return $this->dob->diffInYears(Carbon::now());
}
public function getDOB(){
return $this->dob->format('d-m-Y');
}
Can I not use this method on another controller for Ex- webpagesController, If yes How.
Since you are using a raw query, the data returned is not an object but an array with the data.
Also you did not limit the query, meaning it could return multiple rows.
You'll probably need to get the data from the $users as:
//with the possibily of multiple rows. Index is the row which has to be used
$users[index]['dob']
//when you are sure it only returns one row
$users[0]['dob'] // or $users['dob'] not sure as of the moment
You want to check the differences with Carbon.
So you will probably need to make a Carbon object of the dob result and check it against the Carbon::now.
$age = Carbon::createFromFormat('Y-m-d', $users[0]['dob'])->diffForHumans();
// diffForHumans() uses the local time
Note that this only gets the age for one row (the index or the first because of [0]).
If you want to do it for every row use a for or foreach where you set the $users->age for every $user. But as these are not object/models but raw data, this will not work.
Hope this helps your question a bit

Codeigniter: how to select_avg of multiple columns

I just started with codeigniter and I'm stuck in my database query. I created a simple survey and I want to get the average of the columns. Right now I'm doing it like this to test it:
for($x=1;$x<=5;$x++){
$this->db->select_avg('q'.$x , 'averageq'.$x);
}
$this->db->where('sex','male');
$query = $this->db->get('survey');
$data = $query->row_array();
print_r($data);
The survey will comprise of 30+ questions, is there a shorter way getting the the average of each column? something like:
select_avg('all columns in my answers table);
thank you

Doctrine toarray does not convert relations

I followed doctrine documnetation to get started. Here is the documentation.
My code is
$User = Doctrine_Core::getTable("User")->find(1);
when I access relations by $User->Phonenumbers, it works. When I convert User object to array by using toArray() method, it does not convert relations to array. It simply display $User data.
Am I missing something?
By using the find method you've only retrieved the User data which is why the return of toArray is limited to that data. You need to specify the additional data to load, and the best place to do this is usually in the original query. From the example you linked to, add the select portion:
$q = Doctrine_Query::create()
->select('u.*, e.*, p.*') // Example only, select what you need, not *
->from('User u')
->leftJoin('u.Email e')
->leftJoin('u.Phonenumbers p')
->where('u.id = ?', 1);
Then when toArray'ing the results from that, you should see the associated email and phonenumber data as well.
I also noticed an anomaly with this where if you call the relationship first then call the ToArray, the relationship somehow gets included. what i mean is that, taking your own eg,
$User = Doctrine_Core::getTable("User")->find(1);
$num= $User->Phonenumbers->office; // assumed a field 'office' in your phone num table
$userArray = $user->toArray(true);
In the above case, $userArray somehow contains the whole relationship. if we remove the $num assignment it doesn't.
am guessing this is due to doctrine only fetching the one record first, and it's only when you try to access foreign key values that it fetches the other related tables

Resources