Laravel retrieving data using relationships - mysql

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')

Related

Pivot table for single table in Laravel

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

Mysql Table Relations - Migrations LARAVEL

I am Creating my migrations with laravel, and I have this doubt:
I have these 2 tables:
Cars: ID || || BRAND_NAME || MODEL || YEAR
Brand: ID || NAME
So, if I would like to save Brand ID in my table Cars I use something like that:
$table->integer('brand_id')->unsigned();
$table->foreign('brand_id')->references('id')->on('brand');
All info it saved with a form and it works now. But if I would like to save BRAND_NAME instead of BRAND_ID in my Cars table. It's possible? How I can do this?
If you are specting something like:
$table->string('BRAND_NAME');
$table->foreign('BRAND_NAME')->references('NAME')->on('brand');
Then the answer is no unless your Name field in brand is indexed.
I beleave it is useless to store the name if you are using the brand id on Cars table, but I think the only way to do this is to make a query to get the brand name before you save the car model, something like:
$car = new Car;
$car->brand_id = 1;
$car->brand_name = Brand::find(1)->name;
$car->save();
You can keep your model as it is right now and use the hasOne relationship in Car model, so you can get all brand realted data to each car model. To do this you just need to add in you car model class a method like:
public function brand()
{
return $this->belongsTo('App\Car'); //<--- Put your car model path there
}
With that you can retrieve your Car model with all related brand data with something like:
$user = User::where("id", "=", 1)->with("brand")->first();
Check more info about relationships in https://www.laravel.com/docs/5.3/eloquent-relationships

Nested Query in laravel

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

laravel 5.1 filter using pivot table

Hi i am developing job portal but facing a problem in pivot table filtering. i have a table like below
personal_details
id
name
sex
dob
nationality
visa_status
vacancies
id
name
description
created_at
updated_at
which have a many-to-many relation with pivot table.
Data here is inserted when a job-seeker apply for a vacancy
personal_detail_vacancy
id
personal_detail_id
vacancy_id
created_at
updated_at
PersonalDetail model
class PersonalDetail extends Model
{
public function vacancies()
{
return $this->belongsToMany('App\Vacancy')->withTimestamps();
}
}
Vacancy model
class Vacancy extends Model
{
public function personal_details()
{
return $this->belongsToMany('App\PersonalDetail');
}
what i want to do is select all personal detail who have applied for a job(in any vacancies) in a particular date
i tried
$personal_details = PersonalDetail::with(array('vacancies' => function($query){
$query->wherePivot('created_at', '2015-11-10 11:33:24');
}))->get();
but it is not filtering the date
ANY IDEA?
well solved this by using
$personal_details = PersonalDetail::whereHas('vacancies',function($query)
{
$query->where('created_at','2015-11-10 11:33:24');
})->get();
it was not working before. The problem was i had 'created_at' field in vacancies table also.

Nested Sets Categories with Laravel 4

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