How to solve laravel Relationship - laravel

I am very confused with this relationship, i tried video tutorial but couldn't get how to solve this relationship. Thanks in Advance If someone can explain me.
I tried in mysql that's working fine but i am learning laravel and want to do like this.
User
---------
id
email
name
address1
address2
country
Product
-------
id
internal_name
display_name
Licence
------
id
product_id
key
Linked_licence
--------
licence_id
user_id
User has many licences through linked_licence
I am using like this but getting error :
public function licences()
{
return $this->hasManyThrough(Licence::class, UserLicence::class, 'licences.id', 'user_id', 'licence_id');
}
User has many products through licence
public function licences()
{
return $this->hasManyThrough(Product::class, Licences::class, 'licences.id', 'user_id', 'licence_id');
}
Product belongs to licence
public function licences()
{
return $this->belogsTo(Product::class);
}
This is error :
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'licences_user.licences.id' in 'field list' (SQL: select `licences`.*, `licences_user`.`licences`.`id` from `licences` inner join `licences_user` on `licenscs_user`.`id` = `licences`.`user_id` where `licences_user`.`licences`.`id` is null)
But problem is i don't know about laravel relationship how to create these kind of queries.
Updated :
SELECT
`users`.*,
`licences`.*,
`licenses_user`.`license_id`
FROM `licences`
INNER JOIN `licenses_user` ON `licenses_user`.`license_id` = `licences`.`id`
INNER JOIN users ON licenses_user.user_id = users.id
WHERE `licenses_user`.`license_id` = 1
Above query working but how to use with laravel ?

Your problem seems to be to do with this line of code
Licences::class, 'licences.id', 'user_id', 'licence_id');
it appears that the column does not exist in the table from looking at your error.
double check your spelling, it looks like it's looking inside the table called licences_user for a column named lincences.id

Related

belongsToMany with nullable foreign - Laravel 5.8

in my Laravel project i get this database structure:
Products
Id
Name
Orders
Id
Total
Order_Product
Product_id (nullable)
Order_Id
Details
In my Order model I make belongsToMany retaltionship with Product model:
public function products() {
return $this->belongsToMany(Product::class)->withPivot('Details');
}
The Problem is when I try to get the Order Products Collection
$order->products();
I don't get rows with nullable product_id, Any solution please ? Thank you.
Laravel support "Null Object Pattern" since version 5.5 which allows you to define a default model that will be returned if the given relationship is null.
Try using the following code:
public function products() {
return $this->belongsToMany(Product::class)->withDefault()->withPivot('Details');
}
Most likely, you don't get "nullable" products because you have a relation Order->Products. When you call $order->products(), eloquent tries to get all Product entities that are connected to your Order via product_id field. So, if field is empty, then you can't get Product because there is no connection.
One of the solutions is:
create another entity like OrderLine(Order_Product table); add methods like $orderLine->details() and relation to Product like $orderLine->product()
add relation to OrderLine inside Order - $order->line() or $order->info() etc. -> Order hasMany OrderLine
then use $order->line() to get an order's details and products (if exists)
p.s. I've compiled it in my head so it might need some code adjustments.
Good luck

LARAVEL hasManyThrough still using the ID as foreign key

Hi trying to get the rest day of a country. But I am getting error.
Basically here is the structure
Employee
has SITE,
Site
has REGION,
Region
has REST DAY
I have declared this on my Employee Model
public function restdays()
{
return $this->hasManyThrough('App\ref_restdays', 'App\ref_gacomsit', 'region', 'region');
}
But I get this error
[Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Conversion failed when converting the varchar value 'RUAE' to data type int. (SQL: select [ref_restdays].*, [ref_gacomsit].[region] from [ref_restdays] inner join [ref_gacomsit] on [ref_gacomsit].[id] = [ref_restdays].[region] where [ref_gacomsit].[region] in (855))
Apparently it using still the ID of my site masterfile where as I have declared to use the REGION foreign key.
Can anyone explain where is my mistake is? Appreciate for your help.
Turns out I don't need to use hasManyThrough. I've just declared hasMany on my site masterfile like so:
public function restdays()
{
return $this->hasMany( 'App\ref_restdays', 'region', 'region');
}
then I just use the nested eager loading on my query using dot syntax.
here is my final query, on the last line I just reference site.restdays to get the list of restdays.
$employees = hr_employee::select(
'hr_employee.id',
'empno',
'first_name',
'family_name',
'empstatus',
'empstatus_eff_date',
'contcatg_code',
'post_title_code',
'cs',
'group_initial_joined',
'returned_date',
'mcat2',
'othours1',
'othours2',
'othours3'
)
->where([
['empno','=',$empno]
])
->with(['catg', 'post', 'site.restdays'])
->get();

Query builder - pivot table laravel

How do I get only users from database where they have no role assigned?
User belongs to many roles, the exact relation is:
public function roles() {
return $this->belongsToMany(Role::class, 'user_has_roles', 'user_id', 'role_id');
}
My problem is, that I do only work with Query builder, not with the model so I do not want to use relation.
EDIT:
I am working with migrations, so please no solutions when using model.
You can use doesntHave, I believe this uses QueryBuilder only.
User::doesntHave('roles')->get();
Reference: https://laravel.com/docs/5.6/eloquent-relationships
UPDATE
Using raw SQL query, you can do this.
Basically what this tries to do is to get all users where its id is not found in the user_has_roles table (meaning it doesn't have any relations)
SELECT *
FROM users
WHERE id NOT IN (SELECT user_id FROM user_has_roles)
I think you can convert this into a JOIN or something. I'm not that expert in raw SQL though.
UPDATE Trying Query Builder
$usersWithoutRoles = DB::table('users')
->whereNotIn(function ($query) {
$query->select(DB::raw('user_id'))
->from('user_has_roles')
->whereRaw('user_has_roles.user_id = users.id');
})
->get();
Reference: SQL - find records from one table which don't exist in another
You can try other alternatives there.

How to check and get the result if the table contain user id in laravel

I have create a relationship between user and table column, I want show the table list which is belongs to particular user. For example if user_id 1 is logged in the system, the system will only show the information belong to him which is Table 1.
This is my controller code :
public function show(Request $request){
$user_id=Auth::user()->id;
$table= Roundtable::findOrFail($user_id);
return view('users.tables.show')->withTables($table);
}
I know that $table= Roundtable::findOrFail($user_id); is incorrect but I had no idea how to do because I am new for laravel.
If user has just one table and if Roundtable model has user_id you can use this query:
Roundtable::where('user_id', $id)->first();
It will give you user's table or null if table doesn't exist.
Another way to get table is to use relation:
auth()->user()->roundTable;
Well i found the solution, just need to change the code into
$id=Auth::user()->id;
$table= Roundtable::where('user_id',$id)->get();
return view('users.tables.show')->withTables($table);
then the result will return correctly.

Eloquent - Two Relationships In One?

I've been getting along slowly but surely with Laravel / Eloquent, but am now stumped:
entries Table:
id
user_id
group_id
content
users Table
id
faculty_id
name
group Table:
id
name
faculty Table
id
name
So entries are related to users and groups, and users are related to faculties - I've set up the basic relationships without a problem, and this enables me to find all entries by users from a certain faculty:
Faculty Model:
public function entries()
{
return $this->hasManyThrough('Entry','User');
}
Controller:
Faculty::find(Faculty-ID-here)->entries;
However, I now need to find entries by users that are from a certain faculty AND from a certain group, and I don't know how to write this combination this in Eloquent.
Hope that makes sense! Any suggestions?
Something like:
Entries::whereHas('user', function($q) {
$q->where('faculty_id', $facultyID);
})
->where('group_id', $groupID)
->get();
Assuming you have set up your 'user' relationship.

Resources