ERD :
enter image description here
Model
Student : id
Course : id
Student_Course (payment) : id, student_id, course_id
The relation between Student and Course is Many to Many, because of that I make another table Student_Course.
I have one question, that is Show total amount of students that enroll at least 1 course.
Please help me to find the result. I stuck on that.
can you please try following example:
Model/Student.php //write relationship in your model
public function courses()
{
return $this->belongsToMany(Course::class, 'payment');
}
and then try with following eloquent query
$students = Student::whereHas('courses')
->take(10)
->get();
Try this.
use Illuminate\Database\Eloquent\Model;
class Student extends Model {
public function student_courses() {
return $this->hasMany('App\StudentCourses');
}
}
$students = Student::whereHas('student_courses')->get();
Related
I am both trying to get the review counts and the average review ratings.
I have tables:
Tables:
id
.....
Chairs:
id
.....
Reviews:
id
rating
reviewable_id
reviewable_type
class Review extends Model {
public function reviewable() {
return $this->morphTo();
}
}
class Tables extends Model {
public function reviews() {
return $this->morphMany('App\Review', 'reviewable');
}
public function avg_rating() {
return $this->reviews()
->selectRaw('avg(rating) as avgRating, review_id')
->groupBy('review_id');
}
}
I've tried:
Table::with(['avg_rating'])->withCount('reviews')->where(function($q) use ($regex_terms, $terms){
$q->where('name', 'REGEXP', $regex_terms);
})->get();
But get "Unknown column 'review_id' in 'field list'" or attempting it with variations of "hasmany" yielded only an empty array or an array with the reviews. Just wonder what the best way to accomplish this is or if I'd have to loop through the reviews and calculate manually or a second raw query
I have this but not sure if it is efficient or best practice within Eloquent:
$tables->each(function ($table) {
$table->review_average = DB::table('reviews')
->select(DB::raw("ROUND( avg(rating), 2) as avg"))
->where("reviewable_id", "=", $table->id)->first()->avg;
});
Apparently, I was using Lumen based on the Laravel 6 framework, so it had been throwing a "method not found" error when I tried "withAvg" before. But after searching for that method, I saw that it required a higher version of Laravel. So, updating to Laravel/Lumen 8 allowed me to use the "withAvg" function.
So now my query builder statement looks like:
Table::with(['avg_rating'])->withCount('reviews')->withAvg("reviews", "rating")->where(function($q) use ($regex_terms, $terms){
$q->where('name', 'REGEXP', $regex_terms);
})->get();
Is it possible to make Laravel relation through belongsToMany relations?
I have 4 tables:
1)Restaurants (id , name) - uses hasManyRelation with Workers table
2)Directors (id , name)
3)Directors_Restaurants (id, director_id, restaurant_id) - pivot table for connecting belongsToMany Restaurants with Directors
3)Workers (id, name, restaurant_id)
With this function in Directors model i can get all connected restaurants
public function restaurants()
{
return $this->belongsToMany('App\Restaurant','director_restaurant');
}
With this function in my code i can get all workers of all restaurants of one director
$director = Director::find(1);
$director->load('restaurants.workers');
$workers = $director->restaurants->pluck('workers')->collapse();
So my question is : can i declare similar relation in my Director model to get all its workers of all its restaurants?
Of course you can have hasMany relationship method on Director model with Eager Loading
just like below
public function restaurants()
{
return $this->hasMany(Restaurant::class)->with('restaurants.workers');
}
i can suggest a solution like this:
Director Model OPTION 1
public function getAllRestaurants(){
return $this->hasMany(Restaurant::class)->with('restaurants.workers');
}
Director Model OPTION 2
public function getAllRestaurants(){
$this->load('restaurants.workers');
return $this->restaurants->pluck('workers')->collapse();
}
You can get all restaurants anywhere
$all_restaurants = Director::find(1)->getAllRestaurants();
You can define a direct relationship by "skipping" the restaurants table:
class Director extends Model
{
public function workers()
{
return $this->belongsToMany(
Worker::class,
'director_restaurant',
'director_id', 'restaurant_id', null, 'restaurant_id'
);
}
}
You can define an accessor method in your model to hide some of the logic
# App/Director.php
// You'll need this line if you want this attribute to appear when you call toArray() or toJson()
// If not, you can comment it
protected $appends = ['workers'];
public function getWorkersAttribute()
{
return $this->restaurants->pluck('workers')->collapse();
}
# Somewhere else
$director = Director::with('restaurants.workers')->find(1);
$workers = $director->workers;
But ultimately, you still have to load the nested relationship 'restaurants.workers' for it to work.
Given your table attributes you could also define a custom HasMany relationship that looks like this
# App/DirectorRestaurant.php
public function workers()
{
return $this->hasMany(Worker::class, 'restaurant_id', 'restaurant_id');
}
# Somewhere else
$director = Director::find(1);
$workers = DirectorRestaurant::where('director_id', $director->id)->get()->each(function($q) { $q->load('workers'); });
But I don't recommend it because it's not very readable.
Lastly, there's the staudenmeir/eloquent-has-many-deep package where you can define that sort of nested relationship.
https://github.com/staudenmeir/eloquent-has-many-deep
Laravel Eloquent Query builder problem
Hello I have a problem when I am trying to get all the rows where slug = $slug.
I will explain in more details:
I have two tables, cards and card_categories.
cards has category_id.
card_categories has slug.
What I need is a query which returns all the cards which contents the slugs.
For example I made this:
$cards = Card::leftJoin('card_categories', 'cards.id', '=', 'card_categories.id')
->select('cards.*', 'card_categories.*')
->where('card_categories.slug', $slug)
->paginate(5);
But what happens is that just return 1 row per category.
I don't know what is wrong.
Many thanks.
I think I understand what you mean, from your explanation I would imagine your card model is as follows.
class Card extends Model {
protected $table = 'cards';
public function category()
{
return $this->belongsTo(Category::class)
}
}
In which case, you should just be able to do this:
$cards = Card::whereHas('category', function ($query) use ($slug) {
$query->where('slug', $slug);
})->paginate(5);
That will select all of the cards that has the category id of the given slug.
My tables are like:
shops
[id]
inventories
[id, shop_id]
orders
[id, shop_id]
order_item
[order_id, inventory_id, quantity]
Models:
//Shop
class Shop extends Model
{
public function inventories()
{
return $this->hasMany(Inventory::class);
}
public function orders()
{
return $this->hasMany(Order::class);
}
}
//Inventory
class Inventory extends Model
{
public function shop()
{
return $this->belongsTo(Shop::class);
}
public function orders()
{
return $this->belongsToMany(Order::class, 'order_items')
->withPivot('quantity');
}
}
//Order
class Order extends Model
{
public function shop()
{
return $this->belongsTo(Shop::class);
}
public function inventories()
{
return $this->belongsToMany(Inventory::class, 'order_items')
->withPivot('quantity');
}
}
Now I want 5 top selling inventories of a given shop, What will be the best possible way to do that?
I'm on Laravel 5.5
select s.id,sum(oi.quantity) as total from munna.shops as s
join munna.inventories as iv on s.id=iv.shop_id
join munna.orders as o on iv.shop_id=o.shop_id
join munna.order_items as oi on o.id=oi.order_id
group by s.id
order by total desc limit 5
First, by looking at your tables on order_item, the order_id and inventory_id will bellong to the same shop for sure? I guess yes because if not you would have 2 different shops with same top order. I dont know why you are doing it like this but it's a bit confusing can't figure out why but I would try this:
public function topOrders()
{
$items = DB::table('shops')
->join('orders', 'shops.id', '=', 'orders.shop_id')
->join('inventories', 'shops.id', '=', 'inventories.shop_id')
->join('order_items', 'orders.id', '=', 'order_items.order_id')
->orderBy('quantity', 'desc')
->take(5)
->get();
return $items;
}
What I wrote should select everything from all 3 rows, if you want to select only the items or whatever you want to select you can specify it adding a select clause
Though this was my own question I found the solution on my own and I want to share the solution with the community. I wanted to solve it using Eloquent because I need the model on the view and didn't want to query the model again.
Inventory::where('shop_id', \Auth::user()->shop_id)
->select(
'inventories.*',
\DB::raw('SUM(order_items.quantity) as quantity')
)
->join('order_items', 'inventories.id', 'order_items.inventory_id')
->groupBy('inventory_id')
->get();
I hope this'll help someone with similar issue. Thanks
How can I apply this query in laravel 5?
I have 3 table, Post, Profile, Comments
Post{id,title,body,user_id}
profile{user_id,last_name,first_name}
comments{comments,user_id,post_id}
I want to get this kind of structure:
post_id title post last_name first_name
and below are the comments
comments last_name fist_name
//post model
public function comments(){
return $this->hasMany('App\Comments', 'post_id', 'id');
}
//comments model
public function user(){
return $this->belongsTo('App\Profile', 'user_id');
}
//profile model
public function comments(){
return $this->hasMany('App\Comments');
}
and i call it in the controller using:
$posts = Posts::with('userProfile','comments', 'comments.user')->get();
Then it works:)
Thank you for some help and idea :)
If you need JUST those columns, you have to do something like this:
$users = DB::table('comments')
->join('profile', 'comments.user_id', '=', 'profile.user_id')
->select('comments.comments', 'profile.last_name', 'profile.first_name')
->get();
Anyway, I'd recommend using relations in your models if you are using the data in different places (or different structures).
P.S:
post_id post last_name first_name
There's no "post" field in any table, do you need the post title?