Reputation: 1151
I have 3 models: Client, Task and Taskstatus(for matching tasks for each client).
Model_Task
protected static $_properties = array(
'id',
'name',
'created_at',
'updated_at',
);
Model_Client
protected static $_properties = array(
'id',
'name',
'created_at',
'updated_at',
);
Model_Taskstatus
protected static $_properties = array(
'id',
'client',
'task',
'created_at',
'updated_at',
);
I have added following to Model_Task
protected static $_has_many = array(
'taskstatuses' => array(
'key_from' => 'id',
'model_to' => 'Model_Taskstatus',
'key_to' => 'task',
'cascade_save' => true,
'cascade_delete' => false,
)
);
Model_Client
protected static $_has_many = array(
'taskstatuses' => array(
'key_from' => 'id',
'model_to' => 'Model_Taskstatus',
'key_to' => 'client',
'cascade_save' => true,
'cascade_delete' => false,
)
);
Model_Taskstatus
protected static $_belongs_to = array(
'client' => array(
'key_from' => 'client',
'model_to' => 'Model_Client',
'key_to' => 'id',
'cascade_save' => true,
'cascade_delete' => false,
),
'task' => array(
'key_from' => 'task',
'model_to' => 'Model_Task',
'key_to' => 'id',
'cascade_save' => true,
'cascade_delete' => false,
)
);
I want the taskstatus linked the client field to Client model, and task field to Task model, and if user insert a task with values which are not in Client or Task model (via id), an error should appear. But it does not work (I can still add to clientstatus the value of client's id and task's id that doesn't exist in client and task tables.
Upvotes: 0
Views: 1070
Reputation: 1840
If you stick with the Model convention, the following will work just fine:
class Model_Task extends \Orm\Model
{
protected static $_belongs_to = array(
'client'
);
protected static $_properties = array(
'id',
'name',
'client_id',
'created_at',
'updated_at'
);
}
class Model_Client extends \Orm\Model
{
protected static $_has_many = array(
'task'
);
protected static $_properties = array(
'id',
'name',
'created_at',
'updated_at'
);
}
To get the tasks of a Client, you just have to do:
$client = Model_Client::find(1);
foreach($client->task as $task)
{
/* do something with each $task */
}
Edit: That way you avoid having an unnecessary table/model between Client/Task, forcing you to add valid tasks to existing clients. Besides, if you want a One to Many relationship between Client/Task, using a Model_Taskstatus would allow you to assign the same task to different clients, and that is not what you want.
You should check the Has Many documentation.
Upvotes: 1