One to Many in Laravel - laravel

I have a model in which a Firm has a status. This means there are two tables:
Firm
FirmStatus
I have this defined in my project like this:
class FirmStatus extends Eloquent {
protected $table = 'firm_statuses';
protected $primaryKey = 'firm_status_id';
protected $fillable = array('firm_status_id', 'name');
}
class Firm extends Eloquent {
protected $table = 'firms';
protected $primaryKey = 'firm_id';
protected $fillable = array('name', 'firm_status_id');
public function users()
{
return $this->hasMany('User', 'firm_id', 'firm_id');
}
public function firm_status()
{
return $this->belongsTo('FirmStatus', 'firm_status_id');
}
}
But I can't seem to get this to work, no matter what way I try to access the FirmStatus on the Firm it just doesn't work?
In my controller I have this code:
$firm = Firm::find($id);
$firmClassifications = DB::table('firm_classifications')->orderBy('name', 'asc')->lists('name','firm_classification_id');
return var_dump($firm);
which returns this:
object(Firm)[243]
protected 'table' => string 'firms' (length=5)
protected 'primaryKey' => string 'firm_id' (length=7)
protected 'fillable' =>
array (size=5)
0 => string 'name' (length=4)
1 => string 'firm_classification_id' (length=22)
2 => string 'fca_number' (length=10)
3 => string 'question_number_passed_on' (length=25)
4 => string 'firm_status_id' (length=14)
protected 'connection' => null
protected 'perPage' => int 15
public 'incrementing' => boolean true
public 'timestamps' => boolean true
protected 'attributes' =>
array (size=7)
'firm_id' => int 8
'name' => string 'siofds4' (length=7)
'fca_number' => string '' (length=0)
'firm_classification_id' => int 1
'created_at' => string '2014-09-08 11:06:17' (length=19)
'updated_at' => string '2014-09-08 12:24:23' (length=19)
'firm_status_id' => int 2
protected 'original' =>
array (size=7)
'firm_id' => int 8
'name' => string 'siofds4' (length=7)
'fca_number' => string '' (length=0)
'firm_classification_id' => int 1
'created_at' => string '2014-09-08 11:06:17' (length=19)
'updated_at' => string '2014-09-08 12:24:23' (length=19)
'firm_status_id' => int 2
protected 'relations' =>
array (size=0)
empty
protected 'hidden' =>
array (size=0)
empty
protected 'visible' =>
array (size=0)
empty
protected 'appends' =>
array (size=0)
empty
protected 'guarded' =>
array (size=1)
0 => string '*' (length=1)
protected 'dates' =>
array (size=0)
empty
protected 'touches' =>
array (size=0)
empty
protected 'observables' =>
array (size=0)
empty
protected 'with' =>
array (size=0)
empty
protected 'morphClass' => null
public 'exists' => boolean true
I am expecting that $firm->firm_status (method call or not, whichever way will work) will allow me to access the specified firm status, but $firm->firm_status results in null.

First off, you won't see anything in var_dump($firm) result unless you load the relation.
Next thing - Eloquent requires you to use camelCased methods for relations, if you want to work with dynamic methods (call $model->relation).
So you need:
public function firmStatus()
{
return $this->belongsTo('FirmStatus', 'firm_status_id');
}
then you can access it:
$firm->firmStatus; // FirmStatus model | null
$firm->firm_status; // this will be translated to firmStatus anyway, but not other way around
and to view it in your call:
$firm = Firm::with('firmStatus')->first();
var_dump($firm);
// but better use toArray(), since it's easier to read
dd($firm->toArray());

If a firm can have a single status, use hasOne() instead of belongsTo():
class Firm extends Eloquent {
public function firm_status()
{
return $this->hasOne('FirmStatus', 'firm_status_id', 'firm_status_id');
}
}
If you need to query all of the firms with a given status, add the inverse relationship to FirmStatus:
class FirmStatus extends Eloquent {
public function firm()
{
return $this->hasMany('Firm', 'firm_status_id', 'firm_status_id');
}
}

Related

Laravel 5.8 Call to undefined relationship [sourceClient] on model

I have a model WorkflowStep with a Polyphormic relation to TransportWorkflowStep and TransformworkflowStep
My transportWorkflowStep has an other relation to client.
When I do this in my code:
/** #var TransportWorkflowStep $workflowStepEntity */
$workflowStepEntity = $workflowStep->entity;
try {
var_dump($workflowStepEntity->sourceClient);
} catch (\Exception $exception) {
dd($exception);
}
I get this error:
Call to undefined relationship [sourceClient] on model [App\TransformWorkflowStep].
First weird thing is that I am working with TransportWorkflowStep when I dd($workflowstep) so I don’t know why he’s complaining about TransformWorkflowStep
My WorkflowStep model:
public function entity(): MorphTo
{
return $this->morphTo();
}
My TransportWorkflowStep model:
public function workflowStep(): MorphOne
{
return $this->morphOne(WorkflowStep::class, 'entity');
}
public function sourceClient(): BelongsTo
{
return $this->belongsTo(Client::class, 'source_id', 'id');
}
public function destinationClient(): BelongsTo
{
return $this->belongsTo(Client::class, 'destination_id', 'id');
}
My TransformWorkflowStep model:
public function workflowStep(): MorphOne
{
return $this->morphOne(WorkflowStep::class, 'entity');
}
EDIT
dump of $workflowStepEntity:
object(App\TransportWorkflowStep)[439]
protected 'table' => string 'transport_workflow_steps' (length=24)
protected 'fillable' =>
array (size=4)
0 => string 'source_id' (length=9)
1 => string 'destination_id' (length=14)
2 => string 'source_options' (length=14)
3 => string 'destination_options' (length=19)
protected 'connection' => string 'mysql' (length=5)
protected 'primaryKey' => string 'id' (length=2)
protected 'keyType' => string 'int' (length=3)
public 'incrementing' => boolean true
protected 'with' =>
array (size=0)
empty
protected 'withCount' =>
array (size=0)
empty
protected 'perPage' => int 15
public 'exists' => boolean true
public 'wasRecentlyCreated' => boolean false
protected 'attributes' =>
array (size=8)
'id' => string '4d32e11c-6453-4f48-9419-7c5cbd647128' (length=36)
'source_id' => string '8c826f52-a78c-4ef5-acf5-8e6fd59004a0' (length=36)
'destination_id' => string '921f0d90-2fae-496e-9991-68128e87d6d5' (length=36)
'source_options' => string 'source options' (length=14)
'destination_options' => string 'destination options' (length=19)
'created_at' => string '2019-07-04 11:17:35' (length=19)
'updated_at' => string '2019-07-12 08:39:58' (length=19)
'deleted_at' => null
protected 'original' =>
array (size=8)
'id' => string '4d32e11c-6453-4f48-9419-7c5cbd647128' (length=36)
'source_id' => string '8c826f52-a78c-4ef5-acf5-8e6fd59004a0' (length=36)
'destination_id' => string '921f0d90-2fae-496e-9991-68128e87d6d5' (length=36)
'source_options' => string 'source options' (length=14)
'destination_options' => string 'destination options' (length=19)
'created_at' => string '2019-07-04 11:17:35' (length=19)
'updated_at' => string '2019-07-12 08:39:58' (length=19)
'deleted_at' => null
protected 'changes' =>
array (size=0)
empty
protected 'casts' =>
array (size=0)
empty
protected 'dates' =>
array (size=1)
0 => string 'deleted_at' (length=10)
protected 'dateFormat' => null
protected 'appends' =>
array (size=0)
empty
protected 'dispatchesEvents' =>
array (size=0)
empty
protected 'observables' =>
array (size=0)
empty
protected 'relations' =>
array (size=0)
empty
protected 'touches' =>
array (size=0)
empty
public 'timestamps' => boolean true
protected 'hidden' =>
array (size=0)
empty
protected 'visible' =>
array (size=0)
empty
protected 'guarded' =>
array (size=1)
0 => string '*' (length=1)
protected 'forceDeleting' => boolean false
EDIT full code
WorkflowJob
<?php
namespace App\Jobs;
use App\Workflow;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class WorkflowJob implements ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
/**
* #var Workflow
*/
protected $workflowId;
/**
* Create a new job instance.
*
* #return void
* #param string $workflowId
*/
public function __construct(string $workflowId)
{
$this->workflowId = $workflowId;
}
/**
* Execute the job.
*
* #return \Illuminate\Foundation\Bus\PendingDispatch
* #throws \Exception
*/
public function handle()
{
try {
$this->execute(Workflow::find($this->workflowId));
} catch (\Exception $exception) {
throw $exception;
}
}
/**
* Execute the WorkflowJob.
*
* #param Workflow $workflow
*/
private function execute(Workflow $workflow)
{
// start a new workflow instance
$workflowInstance = $this->startWorkflowInstance($workflow);
// start the first step
StepJob::dispatch($workflowInstance, $workflow->workflowSteps->first()->order);
}
/**
* Start a new WorflowInstance for a Workflow.
*
* #param Workflow $workflow
* #return \Illuminate\Database\Eloquent\Model
*/
private function startWorkflowInstance(Workflow $workflow)
{
return $workflow->workflowInstances()->create([
'started_at' => Carbon::now(),
]);
}
}
StepJob:
<?php
namespace App\Jobs;
use App\Client;
use App\File;
use App\TransportWorkflowStep;
use App\WorkflowInstance;
use App\WorkflowStep;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
class StepJob implements ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
const LOG_START = 'start';
const LOG_END_SUCCESS = 'end';
const LOG_END_FAIL = 'fail';
/**
* #var WorkflowInstance
*/
private $workflowInstance;
/**
* #var int
*/
private $stepCount;
/**
* Create a new job instance.
*
* #param WorkflowInstance $workflowInstance
* #param int $order
*/
public function __construct(WorkflowInstance $workflowInstance, int $order)
{
$this->workflowInstance = $workflowInstance;
$this->stepCount = $order;
}
/**
* Execute the job.
*/
public function handle()
{
if ($this->stepCount <= $this->workflowInstance->workflow->workflowSteps->count()) {
/** #var WorkflowStep $workflowstep */
$workflowstep = $this->workflowInstance->workflow->workflowSteps->where('order', $this->stepCount)->first();
$workflowStepEntity = $workflowstep->entity;
if ($workflowStepEntity instanceof TransportWorkflowStep) {
/* #var TransportWorkflowStep $workflowStepEntity */
try {
var_dump($workflowStepEntity->sourceClient);
} catch (\Exception $exception) {
dd($exception);
}
var_dump($workflowstep->entity->sourceClient);
} else {
$workflowstep->entity->transformer
}
StepJob::dispatch($this->workflowInstance, $this->stepCount + 1);
} else {
return;
}
}
}
workflow_steps
transport_workflow_steps
transform_workflow_steps
You message sais: Call to undefined relationship [sourceClient] on model [App\TransformWorkflowStep].
Your model definition(TransformWorkflowStep):
public function workflowStep(): MorphOne
{
return $this->morphOne(WorkflowStep::class, 'entity');
}
Error message is correct, there is no sourceClient relationship on TransformWorkflowStep model. You should define it or stop using it like this ;)
EDIT:
Could you try to do this:
foreach($workflowStepCollection as $workflowStep)
{
dump($workflowStep->entity);
try
{
$x = $workflowStep->sourceClient;
}
catch(\Exception $ex)
{
dd($ex->getMessage());
}
}
When it fails(dd), the last result before dd should show you exactly which one is going bad.

Cannot access data passed in redirect

so i am using laravel 4.2. my problem is I cannot echo the data from my redirect route. how can i access it the right way? I tried searching to get the right answer but it didn't help me.
public function postLogin()
{
$timeIn = date('Y-m-d G:i:s');
$userLog = New UserLog;
$userLog->username = Input::get('username');
$userLog->time_in = $timeIn;
$userLog->save();
$users = $userLog;
return Redirect::route( 'account' )
->with( 'users', $users );
}
public function account(){
$data = Session::get('users');
var_dump($data );
echo $data->username;// this one throws an error
}
I can see that it has values in var_dump($data).
object(__PHP_Incomplete_Class)[92]
public '__PHP_Incomplete_Class_Name' => string 'UserLog' (length=7)
public 'timestamps' => boolean false
public 'table' => string 'userlogs' (length=8)
protected 'connection' => null
protected 'primaryKey' => string 'id' (length=2)
protected 'perPage' => int 15
public 'incrementing' => boolean true
protected 'attributes' =>
array (size=3)
'username' => string 'user' (length=4)
'time_in' => string '2015-07-28 15:11:43' (length=19)
'id' => int 240
protected 'original' =>
array (size=3)
'username' => string 'user' (length=4)
'time_in' => string '2015-07-28 15:11:43' (length=19)
'id' => int 240
these are my routes file
Route::get('/login', array(
'uses' => 'TimeController#login',
'as' => 'login')
);
Route::post('/postLogin', array(
'uses' => 'SessionsController#postLogin',
'as' => 'postLogin')
);
Route::get('/account', array(
'uses' => 'SessionsController#account',
'as' => 'account')
);
I felt like i made a huge success just by displaying the data, and the problem causing me to get errors is the __PHP_Incomplete_Class as you can see on my var_dump($data) above. To access the $data correctly, i need to unserialize it first before accessing the regular way. here i just added one line of code and everything works very well. thanks to this post unserializing.
public function account(){
$data = Session::get('users');
$data = unserialize(serialize($data)); //added code to unserialize the __PHP_Incomplete_Class
var_dump($data);
echo $data->username;
}
in my var_dump($data) the __PHP_Incomplete_Class is now gone
object(UserLog)[143]
public 'timestamps' => boolean false
protected 'table' => string 'userlogs' (length=8)
protected 'connection' => null
protected 'primaryKey' => string 'id' (length=2)
protected 'perPage' => int 15
public 'incrementing' => boolean true
protected 'attributes' =>
array (size=3)
'username' => string 'user' (length=4)
'time_in' => string '2015-07-28 19:57:08' (length=19)
'id' => int 276
protected 'original' =>
array (size=3)
'username' => string 'user' (length=4)
'time_in' => string '2015-07-28 19:57:08' (length=19)
'id' => int 276

Eloquent query correctly eager loads relation, but when I try to dump the related object I get only the ID

Hey guys I'm trying to grab a relation from the Friend model (pivot for user friends). When I try to dump the relation of the Friend object I should be getting a User model, instead it dumps only the ID of the User.
Here is the Friend Model:
class Friend extends Eloquent
{
public function requester()
{
return $this->belongsTo('Acme\Users\User', 'requester');
}
}
Here is friend repo:
public function getFriendRequests($id, $onlyAccepted = false)
{
return Friend::where('acceptor', $id)->with('requester')->get();
}
Here is FriendsController:
$friendAccepts = $this->friendRepo->getFriendAccepts(Auth::id(), true);
dd($friendAccepts[0]->acceptor);
It should be dumping a User object but I'm only getting the ID of the user when I do:
int 101
Here is output when I dd($friendAccepts[0]);
(It correctly shows the relation eager loaded as a User object
object(Acme\Friends\Friend)[513]
protected 'fillable' =>
array (size=5)
0 => string 'requester' (length=9)
1 => string 'acceptor' (length=8)
2 => string 'status' (length=6)
3 => string 'created_at' (length=10)
4 => string 'updated_at' (length=10)
protected 'table' => string 'friends' (length=7)
protected 'connection' => null
protected 'primaryKey' => string 'id' (length=2)
protected 'perPage' => int 15
public 'incrementing' => boolean true
public 'timestamps' => boolean true
protected 'attributes' =>
array (size=7)
'id' => int 1
'requester' => int 101
'acceptor' => int 1
'status' => int 2
'created_at' => string '2014-05-02 22:53:35' (length=19)
'updated_at' => string '2014-07-31 12:56:53' (length=19)
'deleted_at' => null
protected 'original' =>
array (size=7)
'id' => int 1
'requester' => int 101
'acceptor' => int 1
'status' => int 2
'created_at' => string '2014-05-02 22:53:35' (length=19)
'updated_at' => string '2014-07-31 12:56:53' (length=19)
'deleted_at' => null
protected 'relations' =>
array (size=1)
'acceptor' =>
object(Acme\Users\User)[318]
protected 'fillable' =>
array (size=10)
...
protected 'table' => string 'users' (length=5)
protected 'hidden' =>
array (size=2)
...
protected 'connection' => null
protected 'primaryKey' => string 'id' (length=2)
protected 'perPage' => int 15
public 'incrementing' => boolean true
public 'timestamps' => boolean true
protected 'attributes' =>
array (size=16)
...
protected 'original' =>
array (size=16)
...
protected 'relations' =>
array (size=0)
...
protected 'visible' =>
array (size=0)
...
protected 'appends' =>
array (size=0)
...
protected 'guarded' =>
array (size=1)
...
protected 'dates' =>
array (size=0)
...
protected 'touches' =>
array (size=0)
...
protected 'observables' =>
array (size=0)
...
protected 'with' =>
array (size=0)
...
protected 'morphClass' => null
public 'exists' => boolean true
protected 'pendingEvents' =>
array (size=0)
...
protected 'hidden' =>
array (size=0)
empty
protected 'visible' =>
array (size=0)
empty
protected 'appends' =>
array (size=0)
empty
protected 'guarded' =>
array (size=1)
0 => string '*' (length=1)
protected 'dates' =>
array (size=0)
empty
protected 'touches' =>
array (size=0)
empty
protected 'observables' =>
array (size=0)
empty
protected 'with' =>
array (size=0)
empty
protected 'morphClass' => null
public 'exists' => boolean true
protected 'pendingEvents' =>
array (size=0)
empty
UPDATE:
When I use toArray() and access acceptor as a keyed array element it dumps the user object's properties.
dd(Friend::where('requester', Auth::id())->with('acceptor')->first()->toArray()['acceptor'])
Output:
array (size=7)
'id' => int 1
'requester' => int 101
'acceptor' =>
array (size=14)
'id' => int 1
'email' => string 'nader.verla#johnston.com435' (length=27)
'fname' => string 'April' (length=5)
'lname' => string 'Macejkovic' (length=10)
'username' => string 'AprilMacejkovic40466' (length=20)
'birthday' => string '2006-12-02' (length=10)
'gender' => string 'Male' (length=4)
'location' => string 'Port Noelside' (length=13)
'website' => string 'pagacvandervort.net' (length=19)
'bio' => string 'Ut ut quia vitae vero. Sit eligendi voluptate quia. Voluptas ea accusamus fuga officiis sunt. Sed est fugiat et et voluptas. Distinctio vero error aliquid. Ipsam et tempora asperiores temporibus in autem.' (length=204)
'profile_picture' => string '' (length=0)
'created_at' => string '2013-10-18 09:49:31' (length=19)
'updated_at' => string '2014-03-05 04:17:24' (length=19)
'deleted_at' => null
'status' => int 2
'created_at' => string '2014-05-02 22:53:35' (length=19)
'updated_at' => string '2014-07-31 12:56:53' (length=19)
'deleted_at' => null
You may not want to have relationship methods named the same as table "attributes"(fields) if you plan on using dynamic properties to access those methods.
There is already a mechanism in place to resolve the dynamic properties and inaccesible properties using __get($key) which calls getAttribute($key). The first thing it checks for is if the key exists in the $attributes of the model instance and returns it if it does. This will stop it from continuing to check if there is a relation loaded with that name or if there is a method to call with a camel case version of that key.
"This allows every attribute to dynamically accessed through the _get method without accessors."
Ref
Eloquent Model API
Eloquent Model #__get
Eloquent Model #getAttribute

Object has "Undefined Properties" that are actually defined

I'm using the package: https://packagist.org/packages/gavroche/ups-api
I'm getting some odd behaviors from Laravels Exception Handler when I run this:
$tracking = new \UPS\Tracking(
'KEY', 'USERNAME', 'PASS'
);
$shipment = $tracking->track('TRACKING NUMBER HERE');
foreach($shipment->Package->Activity as $activity) {
var_dump($activity->ActivityLocation->Address->City);
}
The interesting thing is the cities are var_dumped however laravels exception handler, in the same breath, says Undefined property: stdClass::$City.
Here is a vardump of one of the $activity objects:
object(stdClass)[518]
public 'ActivityLocation' =>
object(stdClass)[519]
public 'Address' =>
object(stdClass)[520]
public 'City' => string 'CLEVELAND' (length=9)
public 'StateProvinceCode' => string 'TN' (length=2)
public 'PostalCode' => string '37311' (length=5)
public 'CountryCode' => string 'US' (length=2)
public 'Code' => string 'M4' (length=2)
public 'Description' => string 'RECEPTION' (length=9)
public 'SignedForByName' => string 'HICKMAN' (length=7)
public 'Status' =>
object(stdClass)[521]
public 'StatusType' =>
object(stdClass)[522]
public 'Code' => string 'D' (length=1)
public 'Description' => string 'DELIVERED' (length=9)
public 'StatusCode' =>
object(stdClass)[523]
public 'Code' => string 'KB' (length=2)
public 'Date' => string '20130426' (length=8)
public 'Time' => string '085500' (length=6)
Any property in the $activity->ActivityLocation->Address object laravel sees issue with. However, I can request $activity->Status->StatusType->Description and there are no problems.
A regular for loop fixes the issue. Seems to be some issue in the incrementing of php's foreach().
for ($i=0; $i < (count($shipment->Package->Activity) - 1); $i++) {
var_dump($shipment->Package->Activity[$i]->ActivityLocation->Address->City);
}
You were not clear on this, but are you trying to access this as
$activity->ActivityLocation->Address->City ?
You left the $activity part off your question and used $City and not City, and I wasnt sure if this was intentional or not

Which line tells that collection has some data captured from the database tables?

This what I get using getCollection()
All I can see is model, table node, connection to db etc. But where does it shows that data is here. So that I should know that there is some data returned before looping over. Thank you!
object(Gagan_Faq_Model_Mysql4_Faq_Collection)[616]
protected '_model' => string 'faq/faq' (length=7)
protected '_resourceModel' => string 'faq/faq' (length=7)
protected '_resource' =>
object(Gagan_Faq_Model_Mysql4_Faq)[617]
protected '_resources' =>
object(Mage_Core_Model_Resource)[48]
protected '_connectionTypes' =>
array
...
protected '_connections' =>
array
...
protected '_skippedConnections' =>
array
...
protected '_entities' =>
array
...
protected '_mappedTableNames' => null
protected '_resourcePrefix' => string 'faq' (length=3)
protected '_connections' =>
array
'write' =>
object(Varien_Db_Adapter_Pdo_Mysql)[139]
...
'read' =>
object(Varien_Db_Adapter_Pdo_Mysql)[139]
...
protected '_resourceModel' => string 'faq' (length=3)
protected '_tables' =>
array
'dinkchika' => string 'gagan_faq' (length=9)
protected '_mainTable' => string 'dinkchika' (length=9)
protected '_idFieldName' => string 'faq_id' (length=6)
protected '_isPkAutoIncrement' => boolean true
protected '_useIsObjectNew' => boolean false
protected '_fieldsForUpdate' =>
array
empty
protected '_mainTableFields' => null
protected '_uniqueFields' => null
protected '_serializableFields' =>
array
empty
protected '_fieldsToSelect' => null
protected '_initialFieldsToSelect' => null
protected '_fieldsToSelectChanged' => boolean false
protected '_joinedTables' =>
array
empty
protected '_mainTable' => string 'gagan_faq' (length=9)
protected '_resetItemsDataChanged' => boolean false
protected '_eventPrefix' => string '' (length=0)
protected '_eventObject' => string '' (length=0)
protected '_useAnalyticFunction' => boolean false
protected '_conn' =>
object(Varien_Db_Adapter_Pdo_Mysql)[139]
protected '_defaultStmtClass' => string 'Varien_Db_Statement_Pdo_Mysql' (length=29)
protected '_transactionLevel' => int 0
protected '_connectionFlagsSet' => boolean true
protected '_ddlCache' =>
array
1 =>
array
...
3 =>
array
...
protected '_bindParams' =>
array
empty
protected '_bindIncrement' => int 0
protected '_debug' => boolean false
protected '_logQueryTime' => float 0.05
protected '_logAllQueries' => boolean false
protected '_logCallStack' => boolean false
protected '_debugFile' => string 'var/debug/pdo_mysql.log' (length=23)
protected '_debugIoAdapter' => null
protected '_debugTimer' => int 0
protected '_cacheAdapter' =>
object(Varien_Cache_Core)[20]
protected '_backend' =>
object(Zend_Cache_Backend_File)[17]
...
protected '_options' =>
array
...
protected '_specificOptions' =>
array
...
private '_lastId' (Zend_Cache_Core) => string 'bac_CONFIGURATION_FILES_ACCESS_LEVEL_VERIFICATION' (length=49)
protected '_extendedBackend' => boolean true
protected '_backendCapabilities' =>
array
...
protected '_isDdlCacheAllowed' => boolean true
protected '_ddlColumnTypes' =>
array
'boolean' => string 'bool' (length=4)
'smallint' => string 'smallint' (length=8)
'integer' => string 'int' (length=3)
'bigint' => string 'bigint' (length=6)
'float' => string 'float' (length=5)
'decimal' => string 'decimal' (length=7)
'numeric' => string 'decimal' (length=7)
'date' => string 'date' (length=4)
'timestamp' => string 'timestamp' (length=9)
'datetime' => string 'datetime' (length=8)
'text' => string 'text' (length=4)
'blob' => string 'blob' (length=4)
'varbinary' => string 'blob' (length=4)
protected '_ddlRoutines' =>
array
0 => string 'alt' (length=3)
1 => string 'cre' (length=3)
2 => string 'ren' (length=3)
3 => string 'dro' (length=3)
4 => string 'tru' (length=3)
protected '_intervalUnits' =>
array
'YEARS' => string 'YEAR' (length=4)
'MONTHS' => string 'MONTH' (length=5)
'DAYS' => string 'DAY' (length=3)
'HOURS' => string 'HOUR' (length=4)
'MINUTES' => string 'MINUTE' (length=6)
'SECOND' => string 'SECOND' (length=6)
protected '_queryHook' =>
array
'object' =>
object(Mage_Core_Model_Resource_Setup)[160]
...
'method' => string 'callbackQueryHook' (length=17)
protected '_pdoType' => string 'mysql' (length=5)
protected '_numericDataTypes' =>
array
0 => int 0
1 => int 1
2 => int 2
'INT' => int 0
'INTEGER' => int 0
'MEDIUMINT' => int 0
'SMALLINT' => int 0
'TINYINT' => int 0
'BIGINT' => int 1
'SERIAL' => int 1
'DEC' => int 2
'DECIMAL' => int 2
'DOUBLE' => int 2
'DOUBLE PRECISION' => int 2
'FIXED' => int 2
'FLOAT' => int 2
protected '_config' =>
array
'host' => string 'localhost' (length=9)
'username' => string 'root' (length=4)
'password' => string '' (length=0)
'dbname' => string 'm1' (length=2)
'initStatements' => string 'SET NAMES utf8' (length=14)
'model' => string 'mysql4' (length=6)
'type' => string 'pdo_mysql' (length=9)
'pdoType' => string '' (length=0)
'active' => string '1' (length=1)
'charset' => null
'persistent' => boolean false
'options' =>
array
...
'driver_options' =>
array
...
protected '_fetchMode' => int 2
protected '_profiler' =>
object(Zend_Db_Profiler)[73]
protected '_queryProfiles' =>
array
...
protected '_enabled' => boolean false
protected '_filterElapsedSecs' => null
protected '_filterTypes' => null
protected '_defaultProfilerClass' => string 'Zend_Db_Profiler' (length=16)
protected '_connection' =>
object(PDO)[67]
protected '_caseFolding' => int 0
protected '_autoQuoteIdentifiers' => boolean true
protected '_allowSerialization' => boolean true
protected '_autoReconnectOnUnserialize' => boolean false
protected '_select' =>
object(Varien_Db_Select)[507]
protected '_bind' =>
array
empty
protected '_adapter' =>
object(Varien_Db_Adapter_Pdo_Mysql)[139]
protected '_defaultStmtClass' => string 'Varien_Db_Statement_Pdo_Mysql' (length=29)
protected '_transactionLevel' => int 0
protected '_connectionFlagsSet' => boolean true
protected '_ddlCache' =>
array
...
protected '_bindParams' =>
array
...
protected '_bindIncrement' => int 0
protected '_debug' => boolean false
protected '_logQueryTime' => float 0.05
protected '_logAllQueries' => boolean false
protected '_logCallStack' => boolean false
protected '_debugFile' => string 'var/debug/pdo_mysql.log' (length=23)
protected '_debugIoAdapter' => null
protected '_debugTimer' => int 0
protected '_cacheAdapter' =>
object(Varien_Cache_Core)[20]
...
protected '_isDdlCacheAllowed' => boolean true
protected '_ddlColumnTypes' =>
array
...
protected '_ddlRoutines' =>
array
...
protected '_intervalUnits' =>
array
...
protected '_queryHook' =>
array
...
protected '_pdoType' => string 'mysql' (length=5)
protected '_numericDataTypes' =>
array
...
protected '_config' =>
array
...
protected '_fetchMode' => int 2
protected '_profiler' =>
object(Zend_Db_Profiler)[73]
...
protected '_defaultProfilerClass' => string 'Zend_Db_Profiler' (length=16)
protected '_connection' =>
object(PDO)[67]
...
protected '_caseFolding' => int 0
protected '_autoQuoteIdentifiers' => boolean true
protected '_allowSerialization' => boolean true
protected '_autoReconnectOnUnserialize' => boolean false
protected '_parts' =>
array
'straightjoin' => boolean false
'distinct' => boolean false
'columns' =>
array
...
'union' =>
array
...
'from' =>
array
...
'where' =>
array
...
'group' =>
array
...
'having' =>
array
...
'order' =>
array
...
'limitcount' => null
'limitoffset' => null
'forupdate' => boolean false
protected '_tableCols' =>
array
empty
protected '_cacheConf' => null
protected '_idFieldName' => null
protected '_bindParams' =>
array
empty
protected '_data' => null
protected '_map' => null
protected '_fetchStmt' => null
protected '_isOrdersRendered' => boolean false
protected '_items' =>
array
empty
protected '_itemObjectClass' => string 'Gagan_Faq_Model_Faq' (length=19)
protected '_orders' =>
array
empty
protected '_filters' =>
array
empty
protected '_isFiltersRendered' => boolean false
protected '_curPage' => int 1
protected '_pageSize' => boolean false
protected '_totalRecords' => null
protected '_isCollectionLoaded' => null
protected '_cacheKey' => null
protected '_cacheTags' =>
array
empty
protected '_cacheLifetime' => int 86400
protected '_flags' =>
array
empty
Magento collection won't load until you loop over them, or until you call load. You don't need to worry about looping over an empty collection. If nothing's returned PHP will skip the loop without error
A loaded collection will have a populated $_items array
Collection models have a isLoaded method, which allows you to check if they're loaded
Re: the third item above
$products = Mage::getModel('some/model')->getCollection();
if($products->isLoaded())
{
//,,,
}
else
{
//,,,
}
$collection = Mage::getResourceModel('catalog/product_collection');
$count = $collection->getSize();
Above is standard way magento handles collection.
I have posted for product but for other collections too it uses a different model but almost same function calls.
Your code looks incomplete.

Resources