I'm trying to add a multi-level categories in my website. where a category can have multiple child and also have multiple parent. It's look like many to many relationship in Laravel and I have to use a pivot table.
So that i create a table called categories and also a pivot table categories_reltionship like below. Now my question is how i will make this many to many relationship with this single table in Laravel.
categories table
==================
id title
=== ======
1 title_1
2 title_2
3 title_3
4 title_4
5 title_5
categories_relationship table
==================
parent_id child_id
========== ======
1 2
1 3
4 2
4 3
5 2
5 3
You can have methods like below on Category model :
//This will get you the list of categories
public function categories()
{
return ($this->hasManyThrough('App\Models\Category', 'App\Models\CategoryRelation', 'child_id', 'id', 'id', 'parent_id'));
}
//This will get you the list of children
public function childs()
{
return ($this->hasManyThrough('App\Models\Category', 'App\Models\CategoryRelation', 'parent_id', 'id', 'id', 'child_id'));
}
on CategoryRelation model :
class CategoryRelation extends Model
{
protected $table = 'categories_relationship';
}
I hope this will help you to solve your problem
Note : I suggest you to have 3 tables for many to many relationships,
in many to many relationship you should to have three tables. I hope that help you below example.
in our scenario as mentioned we have three tables with user , role and pivot names that each user can many roles and each role independent to many users.
user table have my_user_id(optional name) and other need column.
role table to have my_role_id (optional name) and other.
pivot table includes my_user_id , my_role_id.
in User model your codes should like below:
class User extends Model
{
public function roles()
{
return $this->belongsToMany('App\Role', 'pivot', 'my_user_id', 'my_role_id');
}
}
in Role model your codes should like below:
class Role extends Model
{
public function users()
{
return $this->belongsToMany('App\User', 'pivot', 'my_role_id', 'my_user_id');
}
}
You can also refer to laravel official documentation:
many to many relationships
Related
In laravel 6, I have 2 models
class Teacher {
}
class Students {
}
I have third model to join tables
class TeacherStudent {
}
Now how can I get all the teachers those are not subscribed by a particular student?
For example:
Teacher1, Teacher2, Teacher3, Teacher4 are in the Teacher table
and
Student1, Student2, Student3, Student4 are in the Student table
Student1 subscribed Teacher1, Teacher2
Student2 subscribed Teacher1, Teacher4
Student3 subscribed Teacher2
Here, as logedin as Student1 when I want to see unsubscribed teachers, I should get Teacher3 and Teacher4
as logedin as Student4 when I want to see unsubscribed teachers, I should get all teachers and so on
I'm assuming you've defined all relations in your models
// in your controller
$user = auth()->user();
// where 'students' is a many-to-many relationship you have in you Teacher model
$teachers = Teacher::whereDoesntHave('students', function($query) use($user) {
return $query
->where('user_id', $user->id);
});
The above query will retrieve all teachers that don't belong to current authenticated user.
In case you haven't defined any relation in your models. They should look something like this:
// Teacher model
public function students() {
// many to many relationship
return $this->belongsToMany('App\Student', 'subscriber'); // replace subscribers with your pivot table
}
An the student model:
// Student model
public function teachers() {
// many to many relationship
return $this->belongsToMany('App\Teacher', 'subscriber'); // replace subscribers with your pivot table
}
PS: haven't tested any of that, let me know if they don't work
The is the table structure,which basically has three tables,namely expenses,categories and sunbcategories
table expenses
(id,category_id,sub_category_id,date,description,amount)
table categories
(id,category_name)
table subcategories
(id,sub_category_name,category_id)
This is the SQL query that is needed
select expense.date, expense.description, expense.amount,
category.category_name, subcategory.sub_category_name
from expenses as expense,categories as category,subcategories as subcategory
where expense.category_id=category.id and
category.id=subcategory.category_id);
This is the function in Expense model with which I pass the category_id
The same query mentioned above is written in laravel, but I am not able to
fetch the data.
function fetchExpenseData($categoryId)
{
$expense = Expense::select("expenses.*","categories.category_name as
Categoryname","subcategories.Sub_category_name")
->join("categories","categories.id","=","expenses.category_id");
->join("subcategories",function($join)
{
$join>on("subcategories.category_id","=","expenses.category_id")
->on("suncategories.id","=","expenses.sub_category_id")
})->get();
return $expenses;
}
$expenses that are returned will be printed in blade.php.
Can I know what is the mistake
thanks in advance
Hye there ,
You need to add eloquent model for retrieving data fromenter code here three tables
Like
I have School Table , Student Table , Teacher Table
School is relating with both Student and Teacher then we will add relationship
In School Model
`
public function getStudent(){
return $this->hasMany('student_id' , App\Student);
}
public function getTeachers(){
return $this->hasMany('teacher_id' , App\Teacher);
}
In Student table
public function getSchool(){
return $this->hasOne('school_id' , App\School);
}
`
now call data from student
`
$students = Student::with('getSchool.getTeachers')->get()
This Demonstration for what I have get from your Question
I have one-to-one relationship between Post and Category. Let me try to illustrate columns. Post columns:
| id | pr_name | pr_description | ..... | `category_id`
And here is Category columns
| id | name
So what am I trying to do is the following. Category is already defined by me and will have only names of Categories. I should retrieve the name of category in my Blade.php file using it's id like this: $post->category->name. But I get error: Trying to get property of non-object. Here are my models: Model of Post
class Post extends Model
{
public function category()
{
return $this->hasOne('App\Like','id','category_id'); // 'id' is foreign key,
// 'category_id' is local key
}
}
Model of Category:
class Category extends Model
{
public function post()
{
return $this->belongTo('App\Post');
}
}
Changed Like to category. And relationship, where Category hasOne('App\Post') and Post model belongsTo('App\Category')
I have two tables:
Table 1: tbluser
ID Name
1 .......... name1
2 .......... name2
3 .......... name3
Another table that links tbluser and tblrole
Table2: tbllinkuserrole
userid..........roleid
1 ............2
1 .......... 2
1 .......... 2
2 .......... 2
3 .......... 1
I would like to fetch the tbluser.Name and the user role from tbllinkuserrole in to a table: a single table row(user record) can have multiple rows inside the column 'role' based on the roles fetched from tbllinkuser role. A user can have multiple roles.
can you help me out...
Laravel have Models (Eloquent), in the model class are some functions that are easy to user to fetch data from table. (this works with Laravel 5.2)
The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table. https://laravel.com/docs/5.2/eloquent
So first of all, you need a User model (php artisan make:model User). You need to link the User modal to the right table.
//File: /laravel/app/User.php
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected $table = 'tbluser';
public function userRoles() {
//Get the table data with the user roles
$this->hasMany('App\UserRoles', 'user_id', 'id');
//First argument gets the UserRoles Modal
//Second argument get the UserRoles column 'user_id'
//Third argument get the User table - column id
}
//File: /laravel/app/UserRoles.php
use Illuminate\Database\Eloquent\Model;
class UserRoles extends Model
{
protected $table = 'tbllinkuserrole';
public function rank() {
//Get the table data with role
$this->hasOne('App\Roles', 'id', 'role_id');
//First argument gets the Roles Modal (table)
//Second argument get the Roles column 'id'
//Third argument get the UserRoles modal (table) - column role_id
}
//File: /laravel/app/Roles.php
use Illuminate\Database\Eloquent\Model;
class Roles extends Model
{
protected $table = 'tblroles';
}
Now if you call Auth::user()->userRoles you will get an array with all rows from table that are linked to the current user.
And when you're running this you dump all the user rank data.
foreach(Auth::user()->userRoles as $userrole) {
{{ dump($userrole) }}
{{ dump($userrole->rank) }}
}
I hope this works for you!
More information can be found on https://laravel.com/docs/5.2/eloquent
TRY THIS ONE
SELECT tbllinkuserrole.userid, tbllinkuserrole.roleid, tbluser.name
FROM tbllinkuserrole, tbluser
WHERE tbllinkuserrole.userid = tbluser.id
The mysql to get the row values as column,
SELECT U.id, U.Name, MAX(CASE WHEN R.roleid = 1 THEN R.roleid END) role_1, MAX(CASE WHEN R.roleid = 2 THEN R.roleid END) role_2 from table_c AS U LEFT JOIN table_b AS R on (U.id = R.userid) WHERE 1 GROUP BY U.id
I have a categories table
CREATE TABLE categories (
name
clean_name
image
description
lft
rgt
)
I need to be able to query all products within a category, organized by sub-categories. In other words:
Products
-Electronics
--Portable
>>> Product 1
>>> Product 2
--TV
>>> Product 1
>>> Product 2
>>> Product 3
So I'd love to be able to loop over Electronics and display the products within their distinctive categories...
So far, all I've been able to do is use a raw query to return the categories, but all on one level, and no products.
Ideally, I'd love to use Eloquent to manage all of this...
Your questions not very clear about exactly what you have set up so far, but essentially you would want:
a categories table with an id and name
a products table with an id, a category_id and a name.
You then need a corresponding model for each:
//category model
Category extends Eloquent
{
public function products()
{
return $this->hasMany('Product');
}
}
//product model
Product extends Eloquent
{
public function category()
{
return $this->BelongsTo('Category');
}
}
You would then grab your categories with your products and perhaps use a nest loop like so:
$categories Category::with('Products')->get();
foreach($categories as $category)
{
echo '<h2>'.$category->name.'</h2>'
foreach($category->products as $product)
{
echo $product->name
}
}
Hope this helps, if not, you'll need to post some more details about what you have so far