Laravel Condition based sql query - mysql

I have three models which are joined. I need to get workspace_members table details only when inventory.status is 1(i.e active).
How can I write that condition in larvel eloquent. Below is my query. Thanks in advance.
$data['inventories'] = Inventory::
Join('category_info','inventory.category_id','=','category_info.category_id')
->leftJoin('workspace_member_inventory', 'inventory.inventory_id', '=', 'workspace_member_inventory.inventory_id')
->leftJoin('workspace_members','workspace_member_inventory.member_id','=','workspace_members.member_id')
->where('inventory.workspace_id', '=', $workspace_id)
->select('inventory.*', 'workspace_member_inventory.member_id','workspace_members.*','category_info.category_name', 'inventory.status as status')
->get()
->toArray();

I don't know if I understood but I think that you are looking for Laravel Query Scopes
Write the scope on your Inventory model:
public function scopeIsActive($query,$status = null){
if(!is_null($status)){
if($status == 1){
return $query->leftJoin('workspace_members','workspace_member_inventory.member_id','=','workspace_members.member_id')->where('inventory.status',1);
}else{
return $query->where('inventory.status',0);
}
}else{
return $query;
}
}
Then add it to your query:
$data['inventories'] = Inventory::
Join('category_info','inventory.category_id','=','category_info.category_id')
->leftJoin('workspace_member_inventory', 'inventory.inventory_id', '=', 'workspace_member_inventory.inventory_id')
->where('inventory.workspace_id', '=', $workspace_id)
->isActive(1)
->select('inventory.*', 'workspace_member_inventory.member_id','workspace_members.*','category_info.category_name', 'inventory.status as status')
->get()->toArray();

Related

SQL Laravel Eloquent - Where field can be uppercase or lowercase

$pname can be "Airbus", "airbus" or "AIRBUS"
$info = Plane::where('plane_name', '=', $pname)
->where('uid', '=', $uid)
->get();
Is there any way I can update this query to check the database for the plane name without case sensitivity?
Use LOWER MYsql function and strtolower php function
$info = Plane::whereRaw('LOWER(plane_name) = (?)', [strtolower($pname)])
->where('uid', '=', $uid)
->get();
OR
Plane::where('plane_name', 'ilike', $pname)->where('uid', '=', $uid)
->get();
just make sure result where clause to lowercase and query clause to lowercase too.
where(DB::raw('lower(column_name)'), '=', Str::lower($query))
dont forget to use:
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
Add -> use Illuminate\Support\Facades\DB; in Controller file.
-----------Example---------------
UserInfo::where(DB::raw('upper(username)'), strtoupper($Request->username))
It's work for me, hope to help you.
To solve my issue, I have to do that on my Model.
simple copy and paste this function
public function __get($key)
{
if (is_null($this->getAttribute($key))) {
return $this->getAttribute(strtoupper($key));
} else {
return $this->getAttribute($key);
}
}

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.

Laravel Query Builder - where clause equals anything programmatically

I'm using Laravel 5.6 - Query Builder.
Is it possible to make a query builder where statement that a value equals everything programmatically?
Let's say that I have this code:
$foo = 1;
DB::table('users')
->select('*')
->where('status', '=', $foo)
->get();
If $foo = 1 then it's straightforward. The query will select everything with the status of 1.
Q: Is it possible to assign something to the $foo variable so the select query returns every record regardless of the status from the DB?
Of course, I can make it happen with 2 query statements like this:
$foo = 1;
if ($foo === null) {
DB::table('users')
->select('*')
->get();
} else {
DB::table('users')
->select('*')
->where('status', '=', $foo)
->get();
}
However, I'm looking for a shorter / more effective solution. Is it possible somehow - without using raw code inside the Where statement?
You may try something like this:
$query = DB::table('users')->select('*');
// $foo = 'get it...';
if ($foo) {
$query->where('status', $foo);
}
$result = $query->get();
Or even more laravel-ish:
$result = DB::table('users')->select('*')
->when($foo, function ($query) use ($foo) {
return $query->where('status', $foo);
})
->get();
Check more here.

Laravel SUBSTRING on Eloquent query

Question
How do I put a limit on one of the rows in an Eloquent result?
Scenario
I need to retrieve only around 100 characters from one of the fields in my result. Currently I'm using a join statement so multiple results are being returned. I basically need only the first 100 characters from post.content
Code
public function getAll()
{
return Post::select('posts.id', 'posts.title', 'posts.content', 'posts.views', 'posts.comments', 'posts.tags', 'posts.date_created', 'users.image_url', 'users.username', 'users.toxick')
->join('users', 'posts.user_id', '=', 'users.id')
->get();
}
I'm not sure how to go about putting a filter on the query to only return 100 characters. I've looked around briefly but I've not found anything useful, not to my specific scenario at least.
Cant test this at the moment (sorry) but what about:
public function getAll(){
$query = Post::select('posts.id', 'posts.title', 'posts.content','posts.views', 'posts.comments', 'posts.tags', 'posts.date_created', 'users.image_url', 'users.username', 'users.toxick')
->join('users', 'posts.user_id', '=', 'users.id')
->get();
foreach($query as $entries){
$entries->content = substr($entries->content, 1, 100);
}
return $query;
}

Retrieve data from one table and order by related table column using Laravel eloquent

I have two models Category and Transaction the table structures are like this
Categories:
id,category_name,..
and
Transactions:
id,category_id,amount..
The relation is
Category hasMany transactions
public function transactions()
{
return $this->hasMany('App\Transaction');
}
Transactions blongsTo Category
public function category()
{
return $this->belongsTo('App\Category', 'category_id');
}
I want to retrieve all data of transaction table which are sorted by category name.
Most importantly I want to get it using the eloquent method.
I have tried eager load which I think doesn't work on the belongsTo relationship.
Here is the code I have used for the eager load.
$transactions = Transaction::with(['category' => function ($query) {
$query->orderBy('category_name', 'asc');
}])->paginate(10);
So far I can achieve this by writing a query like below, but I'd like to use the eloquent method.
$transactions = Transaction::select(DB::raw('transactions.*'))
->leftJoin(DB::raw('(select id,category_name from categories) as categories'), 'categories.id', '=', 'transactions.category_id')
->orderBy('category_name', 'asc')
->paginate(10);
It'd be nice if someone can help me with this. Thank You.
Note: I am using Laravel 5.1
You have to provide the method name that defines the relationship, in your case this is category.
$transactions = Transaction::all()->with('category')->group_by('category.name')->get();
$transactions = Transaction::with('categories')->group_by('category.name')->get();
$cs = Course::where(['courses.active' => 1])
->whereHas('course_dates', function ($join) use ($now) {
$join->where('course_dates.start_date_time', '>', $now);
$join->orderBy('course_dates.start_date_time', 'asc');
})
->whereHas('category', function ($join) use ($cat_slug) {
$join->where('categories.url_slug', '=', $cat_slug);
})
->whereHas('language', function ($join) use ($cat_slug) {
$join->where('languages.string_id', '=', strtoupper(App::getLocale()));
})
->with(['course_dates' => function($q){
$q->orderBy('course_dates.start_date_time', 'desc');
}])
->join('course_dates' ,'course_dates.course_id', '=', 'courses.id')
->orderby('course_dates.start_date_time')
->limit(7)
->get();
To return Eloquent models ordered by related model (hasMany) column, I had to join the tables and then orderBy, still get the models, but correctly ordered by course_date.start_date_time.
Laravel 5.7, I don't think there is a cleaner solution (at least after few hours of tinkering and searching the web).