I have this model code:
class TvguideChannel extends Model{
public function initialize() {
$this->setSource('tvguide_channel');
$this->setConnectionService('db');
$this->hasMany('code', __NAMESPACE__.'\Tvguide', "ch_code", ['alias' => 'Tvguide']);
}
public function getSource() {
return 'tvguide_channel';
}
}
And Controller:
$data = TvguideChannel::find();
$dateDetails = $data->getTvguide(['order' => '$_POST["time"] DESC']);
$paginator = new PaginatorModel(
array(
"data" => $data,
"limit" => $limit,
"page" => $curPage
)
);
$items = $paginator->getPaginate();
This is not working. How I Can use columns from Tvguide model in controller? Thanks for help.
Your controller code will return a TvguideChannel
instance.
To access the relation you have to use the alias you defined above.
$data->Tvguide
The above should contain all Tvguide's for this record.
Here is a more detailed example of hasMany()
:
$this->hasMany(
'id', // The primary key in your main table
'Models\ServicesVideos', // The Model you are joining
'service_id', // Foreign key for main table
[
'alias' => 'videos', // Alias which you use later to access the relation
// additional parameters like where, order, limit etc...
'params' => [
'order' => 'position ASC',
'conditions' => 'type = :type:',
'bind' => [
'type' => get_class($this)
]
]
]
);
UPDATE: example of passing parameters to the relation itself.
Model code:
class Orders extends BaseModel
{
public function initialize()
{
$this->hasMany('id', 'Models\OrderDetails', 'order_id', [
'alias' => 'details',
]);
}
}
Controller code:
// We want only related records with price higher than 9.00
$order = \Models\Orders::findFirst(17);
$orderDetails = $order->getDetails([
'conditions' => 'price > 9.00'
]);
UPDATE 2
find()
method returns a Resulset, which means you can not use directly $data->getTvguide
. You have to iterate over each record and access its related entries.
$data = TvguideChannel::find();
foreach ($data as $item) {
// This will return related guides for each channel.
$dateDetails = $item->getTvguide(...);
}