Relationship il Laravel 8 using three tables - laravel-8

Can some home help me to make this request using laravel Relationship?
SELECT * FROM `recoltes`, `plantations`, `users` WHERE recoltes.plantation_id = plantations.id AND plantations.user_id = users.id;

Yes i found a way
public function recoltes ()
{
return $this->hasManyThrough(Recolte::class, Plantation::class);
}
Note that when i start with ```Plantation::class``` it does not work.
For that to work, You should specify how fields are related between tables

Related

Laravel 8 relationship with two columns in each table

I have a multiple DB connection in Laravel 8 projects, I can't modify one of them which is mainly used in ROR project.
I need to fetch data from two tables only if id1, id2 columns have same value in both the tables. I went on google but did not find anything.
I tried some examples, either it is giving me N+1 query issue or second table o/p always null
function example()
{
return $this->belongsTo(Model::class, 'id1', 'id1')->where('id2', $this->id2);
}
function example()
{
return $this->belongsTo(Model::class, 'id1,id2', 'id1,id2');
}
I came up with a solution from https://laravel.io/forum/06-26-2014-one-to-one-relationship-with-two-fieldscolumns-connection-how
I used join with Laravel relation query:
HouseHold::where("printedcardno","=","17130103-0124")->with(array('members' => function($query)
{
$query->leftJoin('PatientCard', function($join)
{
$join->on('PatientCard.HouseHoldID', '=', 'shp_members.HouseHoldID')
->on('PatientCard.MemberID', '=', 'shp_members.MemberID');
});
}))->get()->take(10)->toArray();
I think this should be good approach as it fixed N+1 query issue and getting desired o/p.

SQL Postgre to show 1 data if get same some multiple data and how to implement to laravel query

i want to ask about sql in postgresql, i got data from join with 3 table, i got the result but i got multiple data like this image
result
and here my sql code in postgresql
select users.* from users inner join model_has_roles on model_has_roles.model_id = users.id
left join roles on roles.id = model_has_roles.role_id where roles.name not in ('job-seeker') order by users.name asc
how to fix this query where i got the multiple data only 1 data to show.
and i want this sql to implement to laravel query and here my code now
public function getAccountList(){
$req = app(Request::class);
// $getAccount = User::query();
$getAccount = User::join('model_has_roles', function($join) {
$join->on('users.id', '=', 'model_has_roles.model_id');
})->leftJoin('roles', function($join){
$join->on('model_has_roles.role_id', '=', 'roles.id');
});
$getAccount->whereNotIn('roles.name', ['job-seeker']);
if ($q = $req->query('q')) {
$searchTerm = trim(strtolower($q));
$getAccount->whereRaw(
'LOWER(users.name) like (?) or LOWER(users.email) like (?)',
["%{$searchTerm}%", "%{$searchTerm}%"]
);
}
// $getAccount->get()->unique('name');
$getAccount->select(['users.*']);
$paginator = $this->pagination($getAccount);
return $this->paginate($paginator, new UserTransformer);
}
how to fix the query only 1 data to show not the multiple same data. thank you for helping me. God Bless You
use distinct()
$data = DB::table('test')->[your query builder]->distinct()->get();
Laravel Query Builder Docs
Just change a bit to make it related to your query builder

SailsJS manually populate records using Model.query

lets say i have this example as my app
http://sailsjs.org/#!/documentation/concepts/ORM/Associations/OnetoMany.html
For some big reasons(complicated) I cannot use Model.populate() and I'm stuck in using Model.query()
Does anyone know how to get the result as User.find().populate('pets') Using Model.query() Please
Thank you
You can do it like waterline adapters do to populate OneToMany:
Retrieve parents : select * from user ...
Retrieve children for each parent in only one query to not overload DBMS:
select * from pet where user = user1.id union select * from
pet where user = user2.id union ... union select * from pet where user
= userN.id.
Regroup children by parentPk(you can use lodash or underscore.js functions to do it) Ex:
users.forEach(function(user){
user.pets = _.filter(pets,function(pet){
return pet.user === user.id;
});
});

How to change Doctrine "findBy/findOneBy" functions's behaviors to reduce the number of queries?

I'm working on a Symfony2 using Doctrine.
I would like to know how to change the behavior of "findBy" functions when retrieving my entities.
For example, if you call "findAll()", it returns all products.
$entities = $em->getRepository('ShopBundle:Product')->findAll();
However, how to reduce the number of queries, because, by default, it will create a new query each time I want to get a member linked to a join column. So if I get 100 entities, it will process 101 queries (1 to get all entities and 1 by entity to get join column).
So today, I use createQuery() function by specifying the joins. Is there a way to configure something about findBy functions to skip createQuery method ?
Thanks in advance !
K4
You can fetch out this in below way
public function findUser() {
$query = $this->getEntityManager()
->createQuery('SELECT us.id as id, us.name as user_name FROM Bundle:User us');
try {
return $query->getResult();
} catch (\Doctrine\ORM\NoResultException $e) {
return null;
}
}

Simple SQL to Eloquent Query (Laravel)

I have two tables: users (Users) and groups (Groups).
Users
-----------------
id | username | group
1 | Bob | 2
Groups
-----------------
id | name
1 | firstgroup
2 | secondgroup
I would like to display: users.ID, users.username, group.name (1, Bob, secondgroup)
An SQL statement like so would work:
SELECT Users.id, Users.username, Groups.name
FROM Users
INNER JOIN
Groups ON Groups.id = Users.group
However, I'm struggling to write this in Eloquent, since there is no "FROM". At the moment I'm going for something along the lines of the below, using JOINS (http://laravel.com/docs/queries#joins)
$users = Users::select('id','username', 'Groups.name')->joins('Groups.id', '=', 'id')->get();
Now this isn't working - I think the joins has to come before the select but I just can't work it out :(
I think you're confusing a few things here...
You're mixing Eloquent with the lower-level DB::table('foo')->select() syntax. When you want to use Eloquent I suggest you take a look at the docs about relationships in Eloquent.
You should define your models like so:
class User extends Eloquent {
public function group()
{
return $this->belongsTo('Group', 'group');
// second parameter is necessary because you didnt
// name the column "group_id" but simply "group"
}
}
class Group extends Eloquent {
public function users()
{
return $this->hasMany('User', 'group');
}
}
This sets up all the joins you might be needing later. You can then simply use User::with('group')->all(); and have the query built and run for you.
Database: Query Builder(DB) is not a Eloquent(ORM):
Database query builder you have to inform the table names and the fields, like it says on in your related link of laravel docs: "...provides a convenient, fluent interface to creating and running database queries." like these query below:
$users = DB::table('users')
->join('contacts', 'users.id', '=', 'contacts.user_id')
->join('orders', 'users.id', '=', 'orders.user_id')
->select('users.*', 'contacts.phone', 'orders.price')
->get();
Eloquent is a ORM - Object related Mapping, it means that your class User is related to the table users (look at you files Migrations) and this class extends the Model Class, thus you can access the methods like these bellow:
class User extends Models
{
public static function usersWithGroups(){
return User::select('id', 'name', 'email')->with('groups')->get();
}
}
Observe that method is into the class User, so you can access that in a static way "User::", using Eloquent you'll have many hidden static methods that will improve you time codding, because you are inheriting de Model methods, to more details visit the Eloquent Docs at: Eloquent Docs