This work perfect:
public function scopeHBO($query)
{
return $query ->where('network', '=', "hbo");
}
Call in Controller: It Works!
$events = Schedule::HBO()->orderBy('searchdate')->get();
When I add another Query Scope like so:
public function scopeHBO($query)
{
return $query
->where('network', '=', "hbo")
->where('searchdate', '>=', 'NOW()');
}
OR:
public function scopeDate($query)
{
return $query->where('searchdate', '>= ', 'NOW()');
}
Then call in the controller:
$events = Schedule::HBO()->Date()->orderBy('searchdate')->get();
I get an error: Undefined variable: event. I tried with with Raw MySql in the same model and it works. Whenever i add a query scope, does not matter what it is.. i get that same error Undefined variable: event.
NOW() is a function, so you need to use a raw query:
where('searchdate', '>=', DB::raw('NOW()'))
Then you can use the scopes. (Do note that I think scopeDate must be called as date(), not Date() - not 100 % sure on that though.)
This sounds less like a generic problem with Laravel, and more like a problem with you specific application.
My guess (which is a wild guess), is that adding that second where clause in your scope method
return $query
->where('network', '=', "hbo")
->where('searchdate', '>=', 'NOW()');
ended up creating a SQL query that returned 0 rows. Then, somewhere in your other code you're doing something like
foreach($events as $event)
{
//...
}
//referencing final $event outside of loop
if($event) { ... }
As I said, this is a wild guess, but the problem doesn't seem to be your query code, the problem seems to be the rest of your code that relies on the query returning a certain number of, or certain specific, rows/objects.
Related
Can someone help me out, I'm trying to do a where query on a Child Model. Everything seems fine when I have a value for the id but it returns nothing when no id is supplied.
My goal is to get all data when no id is supplied and get specific data when id supplied.
Here's my code
Report::with(['project'])
->whereHas('project' function($q) use($programId){
if($programId){
$q->where('program_id', $programId);
}
})->get();
Is there a better way to achieve my goal? or I just lack something on the query? Thank you in advance.
You can use when method for this.
The when method only executes the given closure when the first argument is true. If the first argument is false, the closure will not be executed.
Report::with('project')
->when($programId, function ($query) use ($programId) {
$query->whereHas('project' function($q) use($programId){
$q->where('project.program_id', $programId);
});
})->get();
So I have a little complex answer for this type of questions where you can create a query and do every logic to it.
// Initialise the model
$query = new Report;
// Start building the query
$query->with('project');
// Check if project Id exists
if ($projectId) {
return $query->whereHas('project', function ($subQuery) use ($projectId) {
$subQuery->where('program_id', $programId);
})->get();
} else {
return $query->get();
}
I am putting together a small mailing application within my application, and have run into a strange error - even just following the instructions for the advanced queries. I need to get -just- the mailboxes that are named:
$CoreMailboxes = TableRegistry::get('CoreMailboxes');
$query = $CoreMailboxes->find()
->where(function (QueryExpression $exp, Query $q) {
return $exp->isNotNull('name');
});
$query->hydrate(false);
return $query->toArray();
This is a near duplicate, sans "hydrate: false", of the example in the Cake Cookbook. However, it's giving me an error of
Argument 1 passed to App\Model\Table\CoreMailboxesTable::App\Model\Table\{closure}() must be an instance of App\Model\Table\QueryExpression, instance of Cake\Database\Expression\QueryExpression given
The query in the Cookbook is this:
$query = $cities->find()
->where(function (QueryExpression $exp, Query $q) {
return $exp->isNotNull('population');
});
What am I doing wrong?
You do not need to use the query expression for such a simple query..
You can just put the 'IS NOT NULL' in the where...
Now to re-use the query and create a more usable finder(), expressions may be more useful
$result = $this->Table->find()
->where([
'TableName.column_name IS NOT NULL'
])->toArray();
The problem is the instance definition's of your first argument, the doc is clear:
The passed anonymous function will receive an instance of \Cake\Database\Expression\QueryExpression as its first argument, and \Cake\ORM\Query as its second
Maybe you dont set the correct namespaces of this class, try this:
<?php
use \Cake\Database\Expression\QueryExpression as QueryExp;
//more code
//more code
->where(function (QueryExp $exp, Query $q) {
//more code
I've encounter today same error.
Try to add
use Cake\ORM\Query;
use Cake\Database\Expression\QueryExpression;
at beginning of your controller. It's help in my case.
I also try kip's answer but it doesn't work in my case
I have a search query that needs to be done. However, a search doesn't always have all values set, like in this case.
$aEvents = DB::table('events')
->where('client_id', '=', $client_id);
The question is, how can I make this where statement depend on the value of $client_id. So if the value is empty I don't want the Where statement to occur.
Also, I do not want to write several complete queries with if statements in PHP. To many variables. Ideally I'd like something like this:
$aEvents = DB::table('events')
->(($client_id != "") ? where('client_id', '=', $client_id) : "");
Using eloquent is (really!) nice and save, but I'm not yet up to speed with if statements in std Class objects I guess. Any help is appreciated.
You may try something like this:
$query = DB::table('events');
if(!empty($client_id)) {
$query->where('client_id', $client_id);
}
$aEvents = $query->get(); // Call this at last to get the result
If you are passing client_id to the server via a form/query string(user input) then you may try something like this:
if($client_id = Input::get('client_id')) {
$query->where('client_id', $client_id);
}
Update: For pagination try this:
$aEvents = $query->paginate(10); // For 10 per page
So you may call links() method in your view if you pass it like this:
return View::make('viewName')->with('aEvents', $aEvents);
In the view for pagination links:
$aEvents->links()
You can also use query scopes in the model for this purpose. Scopes allow you to easily re-use query logic in your models. In the model Event, you can add the following query scope:
public function scopeClientID($query, $client_id)
{
if ($client_id != '') {
return $query->where('client_id', '=', $client_id);
} else {
return $query;
}
}
Then from your controller or wherever you're calling it from, you can do the following:
$aEvents = Event::clientID($client_id);
If you want to get all the results, then you can do:
$aEvents = Event::clientID($client_id)->get();
Or if you want pagination, you can do:
$aEvents = Event::clientID($client_id)->paginate();
You can also chain it with other methods like you'd do in a eloquent query.
You can read more about model query scopes at http://laravel.com/docs/eloquent#query-scopes
I am trying to get a column of the last data in the database but so far, I am getting all the data in the database in an array.
This is my code;
public function NewID(){
$adminid=Auth::user()->admin_id;//cooperative ID
$newid = Member::select('member_id')->where('admin_id', '=',$adminid)->get();
return View::make('admin.member.addmember')
->with('NewID', $newid);
}
I have updated the code to be this base on suggestions;
public function NewID(){
$adminid=Auth::user()->admin_id;//cooperative ID
$newid = Member::select('member_id')->where('admin_id', '=',$adminid)->orderBy('id', 'desc')->first();
return View::make('admin.member.addmember')
->with('NewID', $newid);
}
and I am using a For Loop to display data on the view
#foreach ($NewID as $NewIDs)
{{$NewIDs->member_id}}
#endforeach
My error is now ErrorException:Trying to get property of non-object
Answer
I finally got it to work
I used this instead
public function NewID(){
$adminid=Auth::user()->admin_id;//cooperative ID
$newid = Member::select('member_id')->where('admin_id', '=',$adminid)->orderBy('id', 'desc')->take(1)->get();
return View::make('admin.member.addmember')
->with('NewID', $newid);
}
I finally got it to work
I used this instead
public function NewID(){
$adminid=Auth::user()->admin_id;// ID
$newid = Member::select('member_id')->where('admin_id', '=',$adminid)->orderBy('id', 'desc')->take(1)->get();
return View::make('admin.member.addmember')
->with('NewID', $newid);
}
Well, a lot of things could be wrong, so what you should do is find the cause. In you view file, temporarily remove the foreach loop and replace it with {{ dd($NewID) }}. This will 'dump and die' the value of $NewID.
Additionally, I suggest you stick to variable naming conventions. Variables should start lowercase. Also it is confusing to call a collection of Members NewID and a single instance of a member NewIDs. Sticking to the convention helps you and others to read and debug your code.
I have a model called "User", which "belongsToMany" Items.
This relationship works fine, so I can easily do something like this:
User::find(4)->items->find(1)->name
Now, I would like to do something like this:
User::find(4)->items->where('name', '=', 'stick')->get()
I would expect the code to return all the user's items with the name "stick", but unfortunately that is not what happens. I receive this error:
"Call to undefined method Illuminate\Database\Eloquent\Collection::where()"
I also tried to build a query scope:
public function scopeName($query, $name)
{
return $query->whereName($name);
}
The query scope works when I do something like this:
Item::name('SC')->get()
but
User::find(4)->items->name('SC')->get()
still does not work.
Can you help me returning all the user's items, which have the name 'stick'?
If you're looking to just get a single user's items named "stick", this is how you would do it:
$stickItems = Item::whereUserId(4)->whereName('stick')->get();
Here we are using Eloquent's dynamic where methods, but you could rewrite it like so:
$stickItems = Item::where('user_id', '=', 4)->where('name', '=', 'stick')->get();
That should get you what you want.
You have to call the items() method, not use the magic property:
User::find(4)->items()->where('name', 'stick')->get();
// ^^