Kohana pivot tables with additional columns not loading - php

I'm using Kohana v3 with Database and ORM.
I found a nice question which help me add and read additional columns in pivot tables:
Kohana 3.0.x ORM: Read additional columns in pivot tables
I got 2 pivot table with additional column. One of those works perfectly but I'm stuck in the unknown with the second.
Got 2 tables, applications and partners plus my pivot table with the next ORM models:
class Model_Application extends ORM
{
protected $_has_many = array(
'partners'=>array(
'model'=>'partner',
'through'=>'partners_applications',
)
);
}
//AND
class Model_Partner extends ORM
{
protected $_has_many = array(
'applications' => array(
'model'=>'application',
'through'=>'partners_applications',
)
);
}
//plus my pivot table ORM model
class Model_Partners_applications extends ORM
{
protected $_belongs_to = array(
'partner' => array(),
'application' => array()
);
}
When I try to get
$instance = ORM::factory('partners_applications',array('partner_id' => $this->partner,'application_id' => $this->application))->find();
Kohana keep saying :
ErrorException [ Fatal Error ]: Class 'Model_Partners_applications' not found
I've triple checked Model name constructions but I can't find the error.
In Kohana environment debug part, my two firsts models are loaded but not the pivot table.
Any ideas?

Should be ORM::factory('partners_application'), in Kohana ORM always expects singular form ;)

Model_Partners_applications should be inside application/classes/model/partners/applications.php

Related

How to define relation through another relation in Laravel like via() in Yii2?

I need to define one relation through another relation in Laravel so both relations can be eagerly loaded in the optimal way.
For example I have item and attr tables with attr_item intermediate table. In Yii2 I can define one relation through another by using method via:
class Item extends ActiveRecord
{
public function getAttrItems()
{
return $this->hasMany(AttrItem::class, ['item_id' => 'id']);
}
public function getAttrs()
{
return $this-hasMany(Attr::class, ['id' => 'attr_id'])->via('attrItems');
}
}
So when I call $item = Item::find()->with('attrs')->where(['id' => 1])->one() Yii2 makes two additional queries: to table attr_item with condition item_id = 1 and to table attr with identifiers found in previous query. Something like:
SELECT * FROM "item" WHERE "id"=1
SELECT * FROM "attr_item" WHERE "item_id"=1
SELECT * FROM "attr" WHERE "id" IN (1, 2, 3)
After that I have two populated relations: $item->attrs and $item->attrItems.
But I didn't found the same functionality in Laravel. I can define $this->hasManyThrough(Attr::class, AttrItem::class, 'item_id', 'id', 'id', 'attr_id') or $this->belongsToMany(Attr::class, 'attr_item', 'item_id', 'attr_id', 'id', 'id') in Item class but it makes just one query to DB like:
select
"attr".*,
"attr_item"."item_id" as "pivot_item_id",
"attr_item"."attr_id" as "pivot_attr_id"
from
"attr"
inner join "attr_item" on "attr"."id" = "attr_item"."attr_id"
where
"attr_item"."item_id" = '1';
And of course it doesn't hydrate attrItems relation because there is no information about intermediate relation. I can eagerly load both relations attrs and attrItems but in this case the intermediate table attr_item will be used twice and that is not good for performance.
Im not quite sure if this is what you mean but have you looked at 'nested eager loading morph to relationships'?
https://laravel.com/docs/master/eloquent-relationships#eager-loading
Scroll down a bit for 'nested eager loading morph to relationships'.

How to filter associated HABTM data with FriendsOfCake Search for CakePHP 3

Plugin: FriendsOfCake/Search
CakePHP: 3.1.4
I'm using the plugin to filter my index.ctp view data with a form.
This similar question:
How to Filter on Associated Data
is about a belongsTo association. My question is specifically about associated HABTM data where my associated table is linked through a joinTable and not directly. The normal setup in the Model like the following is not working in this case:
->value('painting', [
field' => $this->Paintings->target()->aliasField('id')
)]
My tables are set up like:
Tickets belongsToMany Paintings
Paintings belongsToMany Tickets
with joinTable tickets_paintings
Here is the main setup:
class TicketsTable extends Table
{
public function initialize(array $config)
{
...
$this->belongsToMany('Paintings', [
'foreignKey' => 'ticket_id',
'targetForeignKey' => 'painting_id',
'joinTable' => 'tickets_paintings'
]);
}
public function searchConfiguration()
{
$search = new Manager($this);
$search->value('status', [
'field' => $this->aliasField('active'),
])->like('member_name', [
'field' => $this->Members->target()->aliasField('surname'),
'filterEmpty' => true
])->value('painting', [
'field' => $this->Paintings->target()->aliasField('id'), // not working
]);
return $search;
}
class TicketsController extends AppController
{
public function index()
{
$query = $this->Tickets
->find('search',
$this->Tickets->filterParams($this->request->query))
->contain(['Members', 'Paintings', 'Appointments']);
...
}
Everything else is working and the parameters are added to the URL when I filter etc., so I only put in the parts where sth has to be wrong.
After filtering I get an error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Paintings.id' in 'where clause'
The contain works properly when just displaying data from the Paintings table in the Tickets view.
But in the code from the SQL query I can see, that all contained tables (Members, Appoinments) are joined for the query except the Paintings table, so obviously it can not find the column...And I guess it can't really join it directly anyway since they are only connected through the joinTable.
I'm new to CakePHP and I can't really figure out what I'm doing wrong here, so hopefully someone can help me out a bit.
Do I have to use a different syntax in the plugin settings? Do I have to set up my Tables differently? Or how exactly can I tell the query to incorporate the habtm related table in the search?
Thanks!
The available search methods rely on the field being available in the main query (hasMany and belongsToMany associations are being being retrieved in separate queries).
While you could join it in manually in the controller, using a callback- or a finder-filter is probably the better approach, that way you can modify the query in the model layer, and you could easily utilize Query::matching() to filter by associated data.
Here's an (untested) example that should give you a hint:
use Cake\ORM\Query;
use Search\Type\Callback; // This changed in master recently
// now it's Search\Model\Filter\Callback
// ...
public function searchConfiguration()
{
$search = new Manager($this);
$search
// ...
->callback('painting', [
'callback' => function (Query $query, array $args, Callback $type) {
return $query
->distinct($this->aliasField('id'))
->matching('Paintings', function (Query $query) use ($args) {
return $query
->where([
$this->Paintings->target()->aliasField('id') => $args['painting']
]);
});
}
]);
return $search;
}
See also
https://github.com/FriendsOfCake/search/blob/9e12117404f824847b2d1aa093f3d52736b658b4/README.md#types
https://github.com/FriendsOfCake/search/blob/master/README.md#filters
Cookbook > Database Access & ORM > Retrieving Data & Results Sets > Filtering by Associated Data

Kohana 3 ORM Relationships Question

I've been through several sites (including this one), and unfortunately as a Kohana newbie I still can't get this to work. The data relationship is fairly simple, I have a company record, which should be linked to 1 status record and 1 type record. Of course there will be multiple companies in the table, but each company is only allowed to be linked to 1 of each (and must be).
What I have is:
class Model_Company extends ORM
{
protected $_has_one = array(
'companystatus' => array('model' => 'companystatus', 'foreign_key' => 'entryid'),
'companytype' => array('model' => 'companytype', 'foreign_key' => 'entryid')
,
);
}
Company Status Model:
<?php defined('SYSPATH') or die('No direct access allowed.');
class Model_CompanyStatus extends ORM
{
protected $_table_name = 'datadictionary';
protected $_primary_key = 'entryid';
protected $_has_many = array(
'company' => array('foreign_key' => 'statusid')
,
);
}
?>
Company Type Model:
<?php defined('SYSPATH') or die('No direct access allowed.');
class Model_CompanyType extends ORM
{
protected $_table_name = 'datadictionary';
protected $_primary_key = 'entryid';
protected $_has_many = array(
'company' => array('foreign_key' => 'companytypeid')
,
);
}
?>
The companystatus and companytype models are mapped to a single table which has 2 fields, entryid and entryname. This table is called "datadictionary", and has the appropriate properties so that I don't have to use "id" as the record id field.
Now I load my Company record like this:
$company = ORM::factory('company')
->where('id', '=', 1)
->where('hasbeendeleted', '=', 0)
->find();
The problem is that I don't get anything back for the companystatus and companytype properties for the company, and when I do a $company->companystatus->find() I get the first record returned, which is weird. What am I missing?
Thanks!!
:-)
Edit:
For simplicity's sake the Companies table has the following fields:
ID (primary key) - auto inc int
CompanyName - varchar(255)
StatusID - int
CompanyTypeID - int
HasBeenDeleted - smallint (0 for false, 1 for true)
DataDictionary Table:
EntryID (primary key) - auto inc int
EntryName - nvarchar(255)
Example Company record:
ID: 1
CompanyName: TestCompany
StatusID: 1
CompanyTypeID: 3
HasBeenDeleted: 0
Example DataDictionary records:
EntryID: 1
EntryName: Active
EntryID: 2
EntryName: Inactive
EntryID: 3
EntryName: Customer
EntryID: 4
EntryName: Supplier
There are a few things here I would try changing.
First of all, for readability, most people use underscores in foreign keys. So instead of entryid, I'd recommend using entry_id (you'd have to make the change in both your database and your code).
In Kohana 3, declaring 'model' => 'companystatus' in a $has_one array is redundant when the key is the same as the model name. You can safely remove that part.
But really, that's all incidental to your problem, which exists somewhere between that last ORM call and your database. (I'm assuming here that hasbeendeleted is a column in the company table, not either of the other two tables you mentioned. Let me know if that's not the case.)
If you're doing a ->where('id', '=', 1) together with a ->find(), you're really expecting to return the one company record if it exists in the database. I would recommend making a separate check for hasbeendeleted.
And speaking of which, instead of naming that variable $companies, it should really be singular (e.g. $company) since it will only hold one record.
And you can simplify ORM::factory('company')->where('id', '=', 1) to simply ORM::factory('company', 1)
If you know for sure that a company with a database ID of 1 exists, then the following code should return that record:
$myCompany = ORM::factory('company', 1);
Then you can do something like if ( ! $myCompany->hasbeendeleted) ...
That should help you a bit. Post more details if you run into trouble.

CakePHP HATBM not working

I'm starting a cakephp app, I've never used it in real world so I'm a bit confused how HABTM works, even though I read the documentation I couldn't get even the $this->User->Subscription and didn't see any extra object dumped
What I want is to create a HATBM between users and subscriptions
so I created three tables (users,subscriptions,users_subscribers)
Then in my User.php model I did this
var $hasAndBelongsToMany =
array(
'Subscription' =>
array('className'=>'Subscription',
'joinTable' => 'users_subscribers',
'foreignKey' => 'user_id',
'associationForeignKey' => 'subscription_id',
'unique' => true,
)
);
SUbscription.php
var $hasAndBelongsToMany = array(
'User'=>array('className'=>'User',
'joinTable' => 'users_subscribers',
'foreignKey' => 'subscription_id',
'associationForeignKey' => 'user_id',
'unique' => true));
Even with the tags example and following it, I cannot get the relation set, I also added the line <?php echo $this->element('sql_dump'); ?> to see if its running which it isn't...
Could anyone guide me how exactly you get HATBM to work, what else do I need to verify?
Full code:
pages_controller.php
http://sao.pastebin.com/PWQMhE2z
User model:
http://sao.pastebin.com/PWqwAj1v
Subscription model:
http://sao.pastebin.com/MfVFR4Kw
subscriptions SCHEMA:
http://sao.pastebin.com/mLRcEp1c
User SCHEMA:
http://sao.pastebin.com/UeTRHh3u
users_subscriptions SCHEMA:
http://sao.pastebin.com/4UeSDZte
The simplest and fastest way to get this working is by following CakePHP's rule of configuration over customization.
This means following the CakePHP conventions unless you have a very good reason not to.
I'd strongly recommend starting with a basic setup that you know works, and then modifying that if you need to. Here's a quick and easy way to get up and running.
The Database Tables
Start with three database tables: users, subscriptions and subscriptions_users. The schemas you already have are ok, but I'd make a couple modifications to make sure things go smoothly:
Add a name or title column to the users table. Either that, or you'll have to add the $displayField property to your User model. If you don't do this you'll miss out on some of the "automagic" that CakePHP provides. More info on $displayField
Change the join table's name to subscriptions_users. This is the CakePHP convention and there's no reason not to save yourself the time and worry of following it. :-)
Use the following schema for the join table:
CREATE TABLE subscriptions_users (
subscription_id int(11) NOT NULL,
user_id int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Note that there aren't any keys defined. From the CakePHP manual: "To avoid any issues - don't define a combined primary key for these two fields, if your application requires it you can define a unique index."
The Models
Try to keep your code clean. There are a lot of sensible defaults implemented in CakePHP and there's no point in defining them when they're already defined.
The following models should work for you:
user.php
<?php
class User extends AppModel {
var $hasAndBelongsToMany = array('Subscription');
}
?>
subscription.php
<?php
class User extends AppModel {
var $hasAndBelongsToMany = array('User');
}
?>
Pretty simple. Just be sure your model files are named correctly: user.php and subscription.php, all lowercase.
Also, note that you don't have to set any of the relationship options (className, joinTable, etc.) unless they need to be something besides the default. Ninety percent of the time the defaults should serve you just fine.
You should be up and running now. You can make sure the model objects are being loaded and are accessible in your controllers like this:
users_controller.php
<?php
class UsersController extends AppController {
var $name = 'Users';
function index() {
$this->autoRender = false;
var_dump(is_object($this->User));
var_dump(is_object($this->User->Subscription));
}
}
?>
subscriptions_controller.php
<?php
class SubscriptionsController extends AppController {
var $name = 'Subscriptions';
function index() {
$this->autoRender = false;
var_dump(is_object($this->Subscription));
var_dump(is_object($this->Subscription->User));
}
}
?>
The output of /users and /subscriptions should both be bool(true) bool(true).
You can see the full models by doing pr($this->User);.
Deleting records
If you delete a single record using, for example, $this->User->delete($user_id), all the records in the join table with that user ID will automatically be deleted as well.
If you want to delete a single record from a HABTM join table, without deleting the records that it links to, in effect, "unjoining" the two records, you can do it through the SubscriptionsUser model. This is a model that is created on the fly whenever there's a HABTM relationship.
See here for an example: CakePHP hasAndBelongsToMany (HABTM) Delete Joining Record
I did a test app with a basic schema and I get all the relations right. I suspect your woes have to do with the fact that you did $uses = array('User', 'Subscription');Why don't you try with $uses = $uses = array('User'); and then try
$this->User->find('all');
$this->User->Subscription->find('all');
You also need to define the same HABTM relation in your Subscription.php model. If I recall correctly, CakePHP internally fetches some of the required information from the other side's HABTM configuration.
I always use two "hasMany" relations and one "belongsTo" relation to get the HABTM effect in CakePHP with more control.
Try this:
User model (user.php)
class User extends AppModel {
public $name = 'User';
public $actsAs = array('Containable');
public $hasMany = array('UserSubscription');
}
Subscription model (subscription.php)
class Subscription extends AppModel {
public $name = 'Subscription';
public $actsAs = array('Containable');
public $hasMany = array('UserSubscription');
}
UserSubscription model (user_subscription.php)
class UserSubscription extends AppModel {
public $name = 'UserSubscription';
public $belongsTo = array('User','Subscription');
}
pages/home action (pages_controller.php)
public function home() {
$data = array(
'User' => array(
'id' => 1, 'user_email' => 'allenskd#gmail.com', 'user_password' => 'fdfdkert', 'user_salt' => 'haha', 'user_displayname' => 'David'
),
'UserSubscription' => array(
'user_id' => '1', 'subscription_id' => '1'
),
'Subscription' => array(
'id' => 1, 'title' => 'My first plan', 'price' => '30.00', 'subscriber_count' => '1'
),
);
$this->Subscription->save($data);
$this->User->saveAll($data);
$test = $this->User->find('all', array('contain' => array('UserSubscription' => array('Subscription'))));
pr($test);
}

Kohana ORM Aliasing and "Trying to get property of non-object"

I have the following tables in the database:
teams:
id
name
matches:
id
team1_id
team2_id
I've defined the following ORM models in my Kohana v2.3.4 application:
class Match_Model extends ORM {
protected $belongs_to = array('team1_id' => 'team', 'team2_id' => 'team');
}
class Team_Model extends ORM {
protected $has_many = array('matches');
}
The following code in a controller:
$match = ORM::factory('match',1);
echo $match->team1_id->name; /* <-- */
Is throwing the following error on the linke marked with /* <--- */:
Trying to get property of non-object
The framework is yielding the value of the foreign key instead of a reference to a Match_Model instance as it should (giving the has_many and belongs_to properties stated).
Am I missing something?
Note: Just in case, I've added the irregular plural 'match' => 'matches' in application/config/inflector.php
SOLVED! The Kohana community gave me the answer:
The correct value for the $belongs_to property is:
class Match_Model extends ORM {
protected $belongs_to = array('team1' => 'team', 'team2' => 'team');
}
The documentation states it:
class Blog_Post_Model extends ORM {
protected $belongs_to = array('author' => 'user', 'editor' => 'user');
}
The blog_posts database table would
have 2 columns now,
blog_posts.author_id and
blog_posts.editor_id, and both would
have values that exist in users.id.
It seems that I've missed that line, :)

Categories