I'm studying laravel query builder's "count"
I would like to count column name 'q12a' and 'q18a'
I can count total records useing below code.
public function count()
{
$total_projects = Book::count();
return view('count')->with(['total'=>$total_projects]);
}
However I'm having problem multiple columns
I had been searching count multiple columns and trying below code and I got
Error Call to a member function count() on int
Dear matiaslauriti helping me and I change code as below.
UPDATED
public function sum_ttl()
{
$q18a_count = DB::table('books')->count('q12a')->count('q18a');
return view('sum_ttl', compact('q12a','q18a'));
}
Could you teach me how to write correct code at controller and blade file please?
You are nearly there. count will return the count of your desired columns (* by default). So you want to do something like:
public function sum_ttl()
{
$q12aCount = Books::count('q12a');
$q18aCount = Books::count('q18a');
return view('sum_ttl', compact('q12aCount', 'q18aCount'));
}
If you want to share the exact SQL query you want to execute, I could try to "translate" it to Eloquent.
Related
User Model :
public function favorites()
{
return $this->hasMany(Favorite::class);
}
Controller :
//return auth()->user()->favorites()->get();
//return auth()->user()->favorites;
can someone explain the difference betwen the two codes ?
and when i should use each one?
Let me explain it practically:
If the above query looks like this
// return auth()->user()->favorites()->where('active', true)->get();
// return auth()->user()->favorites->where('active', true);
then its SQL query be like this
// SQL of first query
select * from `favorites` where `favorites`.`user_id` = 1 and `favorites`.`user_id` is not null and `active` = 1
// SQL of second query
select * from `favorites` where `favorites`.`user_id` = 1 and `favorites`.`user_id` is not null
Did you see differences in two SQL?
Now, Let me explain it in words:
If you add some condition after favorites() like above, it will fetch all filtered result from database. But if you add some condition after favorites it will filter the result which is already fetched from the database.
Although, I'm not good at explanations, I hope you understand clearly between the two codes.
I searched all other questions before. I have to simple groupBy select and get sum out of column. But how to make 1 query out of this ( without merge ). Possible?
$Todo = Todo::selectRaw('sum(estimated_time) as amount')->groupBy('user_name')->get();
$Todo = Todo::get()->groupBy('user_name');
I would suggest you avoid using any raw SQL statements in Laravel.
If your goal is to get the sum of the estimated duration of all todos for each user, you can use eager loading.
For example you could first query all your users and eager load the todos.
$users = User::query()->with('todos')->get();
And then you can retrieve the sum of the estimated duration for all todos.
foreach($users as $user) {
$user->totalEstimatedTodoTime = $user->todos->sum('estimated_time')
}
If you use the total estimated todo time of a user often. You could even define an accessor
For example in your user model:
public function getTotalEstimatedTodoTimeAttribute() {
return $this->todos->sum('estimated_time');
}
Then you can retrieve the value like this:
$user->totalEstimatedTodoTime
Write this code in Model :
public function setXXXAttribute($value)
{
$this->XXX= Model::where('user_name' , $this->user_name)->sum('estimated_time');
}
public function getXXXAttribute($value)
{
return $this->XXX
}
I'm studying where queries.
I would like to use two where query. I wrote the below code but I couldn't get any records.
Could you teach me the right code, please?
public function band()
{
$images = ImageGallery::where(DB::raw('LEFT(image, 2)'), '02')->
where(DB::raw('LEFT(image, 2)'), '03')->get();
return view('band',compact('images'));
}
I have a custom attribute on my User model that's calculates the length of some other tables and returns an integer value:
public function GetCurrentQueueLengthAttribute()
{
// return int
}
I then have an API endpoint that returns a "Team" with all its users (simple Spark pivot)
public function show($teamId)
{
$query = Team::query();
$query->with('users')->where('id', $teamId);
$team = $query->first();
return $team->users->sortBy('currentQueueLength');
return $team;
}
The issue is that the returned data doesn't change order. There are no errors, just the same order of the users every time.
Is there something I'm missing?
The sortBy function is not to be mistaken by the orderBy function, the first one sorts a collection, the second one alters the sql of the query builder.
To be able to use the sortBy function one first needs to retrieve the collection. These functions can still be chained by using:
return $team->users()->sortBy('currentQueueLength');
optionally one could also use orderByRaw if you are willing to write a custom sql query for the sorting.
I'm not sure this is a real relation. I will try to explain the best way I can.
So first of all, I have three models :
Appartement,
AppartementPrice
The AppartementPrice depends on :
- appartement_id
I would like the AppartementPrice to be retrieve like that :
If there is a specific price for the appartement, then retrieve it, If not retrieve the price for all appartement which is stored in the database with an appartement_id = 0.
So basically what I would like is to do something like that :
public function price()
{
if(isset($this->hasOne('AppartementPrice')->price) // Check that relation exists
return $this->hasOne('AppartementPrice');
else
return $this->hasOne('AppartementPrice')->where('appartement_id', '0');
}
But this is not working.
It does not retrive me the default price.
I guess anyway this is not a best practice ?
I first tried to get the informations like that :
//Check if appartment has a specific price or retrieve default
if($priceAppartement = AppartementPrice::getPriceByCompanyAppartement($this->id))
return $priceAppartement;
else
return AppartementPrice::getDefaultPrice();
But I had this error :
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
when doing :
echo $app->price->price;
How can I check that a relation exists ? And is there a way to do as I describe ?
Thank you
You can't replace relation like this, as what you intend is not logical - you want to retrieve relation that doesn't exist.
Instead you can do this:
public function getPriceAttribute()
{
return ($this->priceRelation) ?: $this->priceDefault();
}
public function priceDefault()
{
// edit: let's cache this one so you don't call the query everytime
// you want the price
return AppartmentPrice::remember(5)->find(0);
}
public function priceRelation()
{
return $this->hasOne('AppartementPrice');
}
Then you achieve what you wanted:
$app->price; // returns AppartmentPrice object related or default one
HOWEVER mind that you won't be able to work on the relation like normally:
$price = new AppartmentPrice([...]);
$app->price()->save($price); // will not work, instead use:
$app->priceRelation()->save($price);
First of all something really important in Laravel 4.
When you do not use parentheses when querying relationship it means you want to retreive a Collention of your Model.
You have to use parentheses if you want to continue your query.
Ex:
// for getting prices collection (if not hasOne). (look like AppartementPrice)
$appartment->price;
// for getting the query which will ask the DB to get all
//price attached to this appartment, and then you can continue querying
$priceQuery = $appartment->price();
// Or you can chain your query
$appartment->price()->where('price', '>', 0)->get() // or first() or count();
Secondly, your question.
//Appartement Model
// This function is needed to keep querying the DB
public function price()
{
return $this->hasOne('AppartementPrice')
}
// This one is for getting the appartment price, like you want to
public function getAppartmentPrice()
{
$price_object = $this->price;
if (!$price_object) // Appartment does not have any price {
return AppartementPrice->where('appartement_id', '=', 0)->get();
}
return $price_object;
}