laravel advanced join on 5 tables, with 2 tables campared - mysql

I'm not even sure this is possible, I can get it to work up to the 2nd join function, then it just return null.
$articles = DB::table('courses')
->join('version','courses.current_version_id','=','version.id')
->join('category as c1', function($join1){
$join1->on('courses.code','=','c1.title');
})
->join('category as c2', function($join2){
$join2->on('version.version_number','=','c2.title');
})
->join('articleCategories','c2.id','=','articleCategories.cat_id')
->join('articles','articleCategories.article_id','=','articles.id')
->where('c2.parent_id','=','c1.id')
->where('courses.id','=',$course)
->select('courses.code','courses.title','version.version_number','articles.*')
->get();
Is this even possible? What am I getting wrong?

You may try something like this:
$fieldsToSelect = array(
'courses.code',
'courses.title',
'courses.current_version_id',
'version.version_number',
'version.id',
'category.id',
'category.title',
'articleCategories.cat_id',
'articleCategories.article_id',
'articles.*'
);
$articles = DB::table('courses')->join('version', function($join){
$join->on('courses.current_version_id', '=', 'version.id');
})->join('category', function($join) {
$join->on('courses.code', '=', 'category.title')
->on('version.version_number', '=', 'category.title');
})->join('articleCategories', function($join){
$join->on('category.id', '=', 'articleCategories.cat_id');
})->join('articles', function($join){
$join->on('articleCategories.article_id', '=', 'articles.id');
})
->get($fieldsToSelect);

Related

Laravel eloquent double join returning empty

I have a laravel eloquent db query that I would like to return results based on chained join.
$replies = DB::table('model_replies')
->join('support_tickets', function($join){
$join->on('model_replies.model_id', '=', 'support_tickets.id');
$join->where('model_replies.model', '=', DB::raw('"SupportTicket"'));
})
->join('produce_requests', function($join){
$join->on('model_replies.model_id', '=', 'produce_requests.id');
$join->where('model_replies.model', '=', DB::raw('"ProduceRequest"'));
})
->get();
I followed the example from the docs here.
The problem is when I chain the join statements as suggested here my query gives no results.
A single join works just fine. But I need to be able to chain several of them.
What could I be doing wrong?
Thank you!
If I understood it correctly. You want to get support_tickets for those model_replies where model_replies.model = SupportTicket
DB::table('model_replies')
->leftJoin('support_tickets', function($join){
$join->on('model_replies.model_id', '=', 'support_tickets.id');
$join->on('model_replies.model', '=', DB::raw('"SupportTicket"'));
})
->leftJoin('produce_requests', function($join){
$join->on('model_replies.model_id', '=', 'produce_requests.id');
$join->where('model_replies.model', '=', DB::raw('"ProduceRequest"'));
})
->get();

Query builder proper sintax for 4 joins + 3 where clauses (Laravel5.7)

I'm trying to get this MySQL query to work in laravel 5.7 query builder.
It works fine in phpmyadmin
SELECT c.Symbol
, s.SectorName
, cprs.strenght
, s.parentid
, ssbpi.Risklevel
, ssbpi.ColumnType
FROM Companies AS c
JOIN Sectors AS s ON s.SectorID = c.SectorID
JOIN Company_PriceRS AS cprs ON cprs.CompanyID = c.CompanyID
JOIN SubSectorsBPIsData AS ssbpi ON ssbpi.subcategoryid = s.parentid
WHERE cprs.PostDate = '2017-05-08'
AND WHERE CompanyPriceRS.strenght = 'strong'
AND WHERE SubSectorsBPIsData.ColumnType = $ColumnType
ColumnType is a variable that comes from a dropdown and it's already being captured and working properly.
I have tried the normal way according to documentation:
$Completequerytry1 = DB::table('Companies')
->join('Sectors', 'Sectors.SectorID', '=', 'Companies.SectorID')
->join('CompanyPriceRS', 'CompanyPriceRS.CompanyID', '=', 'Companies.CompanyID')
->$join('SubSectorsBPIsData ', 'SubSectorsBPIsData.subcategoryid', '=', 'Sectors.parentid')
->where('CompanyPriceRS.strenght', '=', 'strong')
->where('SubSectorsBPIsData.ColumnType', '=', $ColumnType)
->where('CompanyPriceRS.Postdate', '=', '2017-05-08');
->select('Companies.Symbol', 'Sectors.SectorName', 'CompanyPriceRS.strenght', 'Sectors.parentid', 'SubSectorsBPIsData.subcategoryid','SubSectorsBPIsData.ColumnType')
->limit(10);
->select('Companies.Symbol', 'Sectors.SectorName', 'CompanyPriceRS.strenght', 'Sectors.parentid', 'SubSectorsBPIsData.subcategoryid','SubSectorsBPIsData.ColumnType')
->limit(10);
echo '<pre>';
print_r($Completequerytry1);
Error:
Symfony\Component\Debug\Exception\FatalThrowableError thrown with message "syntax error, unexpected '->' (T_OBJECT_OPERATOR)"
Using functions With several nested joins:
$Completequerytry1 = DB::table('Companies')
->join('Sectors', function ($join) use ($ColumnType) {
$join->on('Sectors.SectorID', '=', 'Companies.SectorID')
->join('CompanyPriceRS', function ($join2) {
$join2->on('CompanyPriceRS.CompanyID', '=', 'Companies.CompanyID')
->join('SubSectorsBPIsData', function ($join3) {
$join3->on('SubSectorsBPIsData.subcategoryid', '=', 'Sectors.parentid')
->where(function ($query1) {
$query1->where('CompanyPriceRS.strenght', '=', 'strong') //filter 1
->where('SubSectorsBPIsData.ColumnType', '=', $ColumnType) //filter2
->where('CompanyPriceRS.Postdate', '=', '2017-05-08'); // filter 3
});
});
});
})
->select('Companies.Symbol', 'Sectors.SectorName', 'CompanyPriceRS.strenght', 'Sectors.parentid', 'SubSectorsBPIsData.subcategoryid','SubSectorsBPIsData.ColumnType')
->limit(10);
echo '<pre>';
print_r($Completequerytry1);
Error:
ErrorException (E_NOTICE)
Undefined variable: ColumnType
3: Then tried functions with nested WHERE
$Completequerytry1 = DB::table('Companies')
->join('Sectors', 'Sectors.SectorID', '=', 'Companies.SectorID')
->join('CompanyPriceRS', 'CompanyPriceRS.CompanyID', '=', 'Companies.CompanyID')
->$join('SubSectorsBPIsData ', 'SubSectorsBPIsData.subcategoryid', '=', 'Sectors.parentid') //ERROR IS GIVEN ON THIS LINE
->where(function ($query1) {
$query1->where('CompanyPriceRS.strenght', '=', 'strong')
->where('SubSectorsBPIsData.ColumnType', '=', $ColumnType)
->where('CompanyPriceRS.Postdate', '=', '2017-05-08');
});
->select('Companies.Symbol', 'Sectors.SectorName', 'CompanyPriceRS.strenght', 'Sectors.parentid', 'SubSectorsBPIsData.subcategoryid','SubSectorsBPIsData.ColumnType')
->limit(10);
echo '<pre>';
print_r($Completequerytry1);
Error:
Undefined variable: join
Still don't know what i'm missing.
Should i create functions for the JOINs and the WHEREs ?
Running out of ideas. Thanks in advance for your insights :)
It turns out that the query was being sent to a variable directly from the controller, not to the view.
I was doing this only for testing but it was using too much memory with print_r(); function making impossible to get a result. Even when using dd(); i wasn't getting what i wanted (I think it's because some sintax errors i had).
So i passed the final variable to the view and it works fine since laravel could handle the data differently.
Also i used ->limit(10); to split the results and avoid memory overload.
Here is the final code working:
$Completequerytry1 = DB::table('Companies')
->join('Sectors', 'Sectors.SectorID', '=', 'Companies.SectorID')
->join('Company_PriceRS', 'Company_PriceRS.CompanyID', '=', 'Companies.CompanyID')
->join('SubSectorsBPIsData', 'SubSectorsBPIsData.subcategoryid', '=', 'Sectors.parentid')
->select('Sectors.SectorName', 'Companies.Symbol', 'Company_PriceRS.strenght', 'Sectors.parentid', 'SubSectorsBPIsData.Risklevel','SubSectorsBPIsData.ColumnType')
->where('Company_PriceRS.strenght', '=', 'strong')
->where('SubSectorsBPIsData.ColumnType', '=','X')
->where('Company_PriceRS.Postdate', '=', '2017-05-08')
->limit(10)
->get();
return view('besttrades2', array('Completequerytry1' => $Completequerytry1)); //sending my query variable to the view
Then in the view only used:
<?= $Completequerytry1; ?>
or show it in whatever way you want.
Sometimes it's better to have another project only for testing separately.

How to use OR inside WHERE in laravel Query

I'm new to laravel and I need help for query in laravel
My Custom Query
$sql1="SELECT * FROM blogs
WHERE
('$title'='' OR title='$title')
AND
('$body'='' OR body='$body')";
and i create a laravel build query but don't know how to put OR inside WHERE and Put Brackets
$posts = Blog::where('title','LIKE',"%{$title}%")
->Where('body', 'LIKE',"%{$body}%")
->offset($start)
->limit($limit)
->orderBy($order,$dir)
->get();
I think orWhere is what you're looking for and based off custom query I think you would need = instead of like unless thats what youre going for, I think it would be something like:
->where('title', '=', $title)
->orWhere('title', '=', '');
$posts = Blog::where(function($q) use($title){
$q->where('title','')->orWhere('title',$title);
})->where(function($q) use($body){
$q->where('body','')->orWhere('body',$body);
})->offset($start)
->limit($limit)
->orderBy($order,$dir)
->get();
Just use orWhere()
$posts = Blog::where('title', $title)
->orWhere('title', $otherTitle)
->orderBy($order, $dir)
->get();
Your query should be like :
$result = Blog::where(function($query) use ($title, $body){
$query->where(
["title" => $title, "body"=>$body]
)->orWhere(
["title"=>"", "body"=>""]
);
})
->offset($start)
->limit($limit)
->orderBy($order,$dir)
->get();
Hope this give you an idea :)
$posts = Blog::where(function ($query) use($title) {
$query->where('title', 'LIKE', "%{$title}%")
->orWhere('title', '=', '$title');
})
->orWhere(function ($query) use($body) {
$query->where('body', 'LIKE', "%{$body}%")
->orWhere('body', '=', '$body');
})
->offset($start)
->limit($limit)
->orderBy($order,$dir)
->get();
Not tested...
Use the ->orWhere() code.
Note: You can also make use of magic methods
->whereAgeOrPhone(18, 123456789);
use orWhere()
$blogs= DB::table('Blog')
->where('title', 'LIKE', '%{$title}%')
->orWhere('body','LIKE', '%{$body}%')
->offset($start)
->limit($limit)
->orderBy($order,$dir)
->get();
For More Query, You can visit here

InvalidArgumentException in JoinClause.php line 79: Not enough arguments for the on clause

I did query builder with laravel and I've used multiple join in it. When execute the query I get the error Not enough arguments for the on clause.
My query builder:
return DB::table('towns_cat_rel')
->join('towns', function ($join) {
$join->on('towns_cat_rel.town_id', '=', 'towns.id')
->where('publish', '=', 1);
})
->join('towns_translations', function ($join) {
$join->on('towns_cat_rel.town_id', '=', 'towns_translations.town_id')
->where('locale', '=', \App::getLocale());
})
->join('towns_cat', function ($join) use($categoryID) {
$join->on('towns_cat.id', '=', 'towns_cat_rel.town_cat_id')
->where('towns_cat.id', '=', $categoryID);
})
->join('towns_sub_cat_rel', 'towns_cat_rel.town_id', '=', 'towns_sub_cat_rel.town_id')
->join('towns_sub_cat', function ($join) use($subCategoryID) {
$join->on('towns_sub_cat_rel.town_sub_cat_id', 'towns_sub_cat.id')
->where('towns_sub_cat.id', '=', $subCategoryID);
})
->get();
Does anyone know why this happen?
Sorry Guys! I had forget '=' in the last join => $join->on('towns_sub_cat_rel.town_sub_cat_id', '=', 'towns_sub_cat.id')
Now it works fine!
I am using laravel5.2 and facing this above error message due to this above code and i resolved with this code, you can modify as per your requirement.
DB::table('users')
->join('contacts', function ($join) {
$join->on('users.id', '=', 'contacts.user_id')->orOn(...);
})
->get();

Limit JOIN to 1

I am trying to pick out Shops with the specified $item_id.
An Item can have multiple Images, but I only want the first one.
The current code gives me only the first image, but it duplicates the item as many times as there are images.
Here's the code:
$shops = Shop::with(array('items' => function($query) use ($item_id) {
$query->select('items.id', 'items.name', 'items_images.path AS image');
$query->join('items_images', 'items.id', '=', 'items_images.item_id');
$query->where('items.id', '=', $item_id);
}))
->get(array('shops.id', 'shops.shop_name', 'shops.lat', 'shops.lng'));
And the current output:
How can I avoid getting all the duplicates?
I think this will work.. I haven't done much at all with this syntax but I think this is how it would work (assuming main is in the items_images table)
$shops = Shop::with(array('items' => function($query) use ($item_id)
{
$query->select('items.id', 'items.name', 'items_images.path AS image');
$query->join('items_images', function($join)
{
$join->on('items.id', '=', 'items_images.item_id')
->where('items_images.main', '=', 1);
})
$query->where('items.id', '=', $item_id);
}))->get(array('shops.id', 'shops.shop_name', 'shops.lat', 'shops.lng'));
Found the DOCS on it... if you want to include it in the JOIN then it looks like you have to add a where to the JOIN