I include the region and category language of category table in the builder. The region returns the exact output that I want, but the category language always returns empty. I copy the query and run it to Postgres and it returns some data.
Query
Relation of region and category language to category table
Output
Category Language Schema
Executed query for Category Language Table in Postgres. Working fine here
CategoryLanguageRegion Model
I think you have to add category_id in select query as follows:
'categoryLanguages' => functon($query) {
$query->select('id', 'title', 'description', 'category_id');
}
For region, you don't have to add because mapping is other way around. It's Category model that contains foreign key region_id, but for CategoryLanguage, Category model doesn't have any foreign key that's why you have to explicitly add category_id in select query.
Related
I have four models: User, Product, Order, OrderItem
When a User adds an item to his cart, it creates a new Order and the item becomes a new OrderItem.
The tables:
users
id - integer
name - string
products
id - integer
name - string
orders
id - integer
user_id - integer
paid - boolean
order_items
order_id - integer
product_id - integer
quantity -integer
price - double
Relationships:
`Product` hasMany `OrderItem`
`OrderItem` belongsTo `Order`
`OrderItem` belongsTo `Product`
`Order` hasMany `OrderItem`
`User` hasMany `Order`
I want to be able to list all Product and under each, all the Users who bought that Product (Order whereNotNull 'paid').
Inversely, I'd like to show a User all the Products they have purchased.
I've tried taking it in steps with relationships. I can get {{ $product->orderItems }} to work, but not {{ $product->orderItems->orders }}
Laravel doesn't allow hasManyThrough relationships with a pivot table, which is essentially what order_items is, so that won't work.
Maybe I could do this with an Accessor with a join, but I can't wrap my head around it because I can't really set the relationship.
Maybe a custom Eloquent collection so every time I call Product it already has all the paid User and every time I call User the collection will already have all his Product?
Laravel has no native support for a direct relationship.
I've created a package for cases like this: https://github.com/staudenmeir/eloquent-has-many-deep
class Product extends Model
{
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function users()
{
return $this->hasManyDeep(
User::class,
['order_items', Order::class],
[null, null, 'id'],
[null, null, 'user_id']
)->whereNotNull('orders.paid');
}
}
$users = Product::find($id)->users;
Suppose I have a Laravel 5.5 app with four models:
Class, Student, Assignment and AssignmentSubmission
A Class belongs to many Students, a Student belongs to many Classes and an AssignmentSubmission belongs to an Assignment, a User, and a Class.
So the tables look like this:
classes:
id
name
students:
id
name
class_student:
class_id
student_id
assignments:
id
name
assignment_submissions:
id
class_id
student_id
assignment_id
Now, in a query builder class I need to construct a query that returns the Students that belong to a Class with an extra column called total_assignment_submissions with a tally of how many assignments that student has submitted for that class only.
My first port of call was the following:
$class->students()->withCount('assignmentSubmissions')->get();
But that returns the total assignment submissions for that student for all classes.
The following mySql query returns the right data:
SELECT *,
(SELECT Count(*)
FROM `assignment_submission`
WHERE `student_id` = `students`.`id`
AND `class_id` = ?) AS total_assignment_submissions
FROM `students`
INNER JOIN `class_student`
ON `students`.`id` = `class_student`.`student_id`
WHERE `class_student`.`class_id` = ?
But I can't seem to get the selectSub() addSelect() and raw() calls in the right order to get what I want. It seems that I only do it with raw queries but the event id will be unsanitized or otherwise I can do it but it only returns the assignment_count field and not the rest of the fields for the student.
$class->students()
->selectSub(
AssignmentSubmission::selectRaw('count(*)')
->whereClassId($class->id)->getQuery(),
'total_assignment_submissions'
)->toSql();
There must be a way to do this. What am I missing here?
withCount() can be constrained.
$class->students()->withCount(['assignmentSubmissions' => function($q) use($course_id){
$q->where('course_id', $course_id);
}])->get();
This will limit the count to that particular course.
I have one table employee_profile, I am using this table for searching employees, it's columns are id, user_id, experience, salary.
I have two more tables
employee_keyskills with columns user_id and keyskills_id
employee_preferred_cities with columns user_id and city_id
Now I have to find employees with experience, salary, keyskills[], salaries[]
Just I need help in finding results from hasMany associated tables, means employees should be filtered only with specified keyskills[] and cities[] from employee_keyskills and employee_preferred_citites tables.
you should use whereHas which allow you to add customized constraints to a relationship constraint.
check this
https://laravel.com/docs/5.4/eloquent-relationships#querying-relationship-existence
I have two models, Product and Attribute. There is a 'product_attributes' joining table between 'products' and 'attributes'. The relationship is defined in both models using belongsToMany(), and the key of the table is a compound one of product_id and attribute_id.
I can successfully retrieve and store records in the joining table - so, as such everything is functioning as expected, with the exception that the created_at and updated_at in product_attributes is not being set.
Is the above by design, and is there anything I can do to rectify this?
You should use the belongsToMany function with the timestamps declaration like this:
$this->belongsToMany(<entity>)->withTimestamps();
I have subject table that contains
id name
and languages table that contains
id subject_id
and division table
id name
finally subject-division table (pivot table)
id subject_id division_id
now exist one-To-one relationship between subject table and languages table and many-To-many relationship between subject table and division table, i need to pluck only the subjects of subject table without the languages by using the relationship function
now i can get the languages only of the subject table of the relationship function In Division Model as the following
public function langSubject ()
{
return $this->belongsToMany('Subject' , 'subject_division','division_id','subject_id')
->join('lang_subject', 'lang_subject.subject_id' ,'=', 'subject.id')->get();
}
But till now I can't get the subjects only without the languages
Any Suggestions ?
You need to add the clause ->select('tableName1.fieldName1','tableName2.fieldName2','tableName3.fieldName3') to your statement after the join statement to get the tableName.fieldName and you may need to use leftJoin instead of join to get the results whether if there is a match or not.
Check out Eloquent relationship documentation -> sub headline "Querying Relationship Existence". There it mentions ::has method, which you could use in fashion
Division::has('subject.lang', '<', 1)->get()
Or at least that's the theory. Haven't had the need for it yet ;-)
It should be supported by Laravel 4 as well.