Kohana 3.1 ORM: joins for has_many - kohana-3

I have a users, messages and comments.
users id user_id
messages id user_id
comments id message_id
I can get users data of the message using with().
$model = ORM::factory('message');
$messages = $model
->with('user')
->find_all();
with('comment') doesn't work. I guess because it's created for one-to-one relations while I have message has_many comment.
How do I get comments data into $messages? Like the following: ['message_id']['comment_id'][DATA]?

0. Define relationships:
User has_many Messages
Message has_many Comments
Message belongs_to User
Comment belongs_to Message
class Model_User extends ORM {
protected $_has_many = array('messages' => array());
}
class Model_Message extends ORM {
protected $_belongs_to = array('user' => array());
protected $_has_many = array('comments' => array());
}
class Model_Comment extends ORM {
protected $_belongs_to = array('message' => array());
}
1. Get user messages:
$messages = ORM::factory('user', $user_id)->messages->find_all();
foreach($messages as $message) {...}
2. Get message owner:
$user = ORM::factory('message', $message_id)->user; // without find_all()!
3. Get message comments:
$comments = ORM::factory('message', $message_id)->comments->find_all();
foreach($comments as $comment) {...}

Related

How can cart table associate with another table?

I have table table_name(id, cart_token, data , created_at, updated_at ) that wants to associate with shopware cart table using token column (table_name.cart_token = cart.token).
How can we do this association using DAL as long as cart table doesn't have a CartEntity and CartDefinition.
For example: Select * from table_name leftjoin cart on table_name.cart_token=cart.token where cart.token=null.
Without a definition and accompanying entity class you simply won't be able to retrieve the cart as a mapped object using the DAL. You could add your own definition and entity for the cart table but I wouldn't recommend it, as this would just cause problems if multiple extensions got the same idea. I would recommend injecting Doctrine\DBAL\Connection in a service of your plugin and just fetching the cart using raw SQL.
class CartFetcherService
{
private Connection $connection;
public function __construct(Connection $connection)
{
$this->connection = $connection;
}
public function fetchCart(YourCustomEntity $entity): ?array
{
$cart = $this->connection->fetchAssociative(
'SELECT * FROM `cart` WHERE `token` = :token',
[
'token' => $entity->getToken(),
]
);
return $cart ?: null;
}
}
If you want to retrieve the Cart object directly, you could also inject the Shopware\Core\Checkout\Cart\CartPersister service to load the cart.
class CartLoaderService
{
private CartPersister $persister;
public function __construct(CartPersister $persister)
{
$this->persister = $persister;
}
public function getCart(YourCustomEntity $entity, SalesChannelContext $context): ?Cart
{
try {
$cart = $this->persister->load($entity->getToken(), $context)
} catch (\Throwable $exception) {
$cart = null;
}
return $cart;
}
}

Allowed fields must be specified for model how to fix the error?

I am new to code igniter 4 user. and faced these type error please any one help to me.. how to fix the error.
CodeIgniter\Database\Exceptions\Data Exception
Allowed fields must be specified for model: App\Models\Student Model
look at my model
works for me fine
<?php namespace Modules\App\Models;
use Modules\App\Entities\CourseCategoryEntity;
use CodeIgniter\Model;
use Modules\Shared\Models\Aggregation;
class CourseCategoryModel extends Aggregation
{
/**
* table name
*/
protected $primaryKey = "id";
protected $table = "course_category";
/**
* allowed Field
*/
protected $allowedFields = [
'name',
'language'
];
protected $returnType = CourseCategoryEntity::class;
protected $validationRules = [
'name' => 'required|min_length[3]|max_length[255]',
'language' => 'required|min_length[1]|max_length[255]',
];
protected $useSoftDeletes = false;
protected $validationMessages = [];
protected $skipValidation = false;
}

TypeORM: duplicate key while saving relationships with existing entities

I have the following entity in TypeORM:
#Entity('category')
export class Category {
#Column({ length: 80 })
public name: string;
#OneToOne(
(): ObjectType<Category> => Category,
(category: Category): Category => category.parent,
{
cascade: ['insert', 'update'],
}
)
#JoinColumn({ name: 'parent', referencedColumnName: 'id' })
public parent: Category;
}
Next, I save some categories in my database:
let parentCategory = new Category();
parentCategory.name = 'Parent Category';
let childCategory = new Category();
childCategory.name = 'Child Category';
childCategory.parent = parentCategory;
connection.manager.save(childCategory);
Finally, I want to add a new child category of "Parent Category" (consider the parent category was loaded from the database and contains its ID):
let newChildCategory = new Category();
newChildCategory.name = 'New Child Category';
newChildCategory.parent = childCategory.parent; //<- childCategory.parent contains the parent ID
connection.manager.save(newChildCategory); //<- Throws duplicate key error due to cascade
One viable solution is defining the ON DUPLICATE KEY behaviour, which must be implemented manually according to this information. Is there another solution to do it while saving the entity without having to write the whole query as in my example?
This GitHub repository contains an application replicating the issue.
Can you try
#ManyToOne(
type => Category,
category => category.children,
{
cascade: ['insert', 'update'],
}
)
public parent: Category;
#OneToMany(
type => Category,
category => category.parent,
{
cascade: ['insert', 'update'],
}
)
public children: Category[];
?
I'm not sure it's the root cause of your problem, but parent's type should be Category and not category. It's strange that you IDE didn't warn you btw.
Watch out, though, because you defined your category-parent relation to be of OneToOne type, but from the example you provided you're using it as a OneToMany/ManyToOne relation!

Kohana 3 - Save model to DB with relation belongs_to

I have a simple problem but I can not find an answer anywhere - neither in the documentation nor in this forum.
In short - I have 2 models in Kohana 3 - Task and TaskType.
I would like to create a Task model in such a way that I can then refer to the field $ task-> task_type_id-> name.
Unfortunately, when you insert a record into the database, I get the answer:
"General error: 1364 Field 'task_type_id' does not have a default value"
When I add the task_type_id field as a normal field (in $ _table_columns), then I can not refer to the TaskType object in the view via $ task-> task_type_id-> name.
I do not know how to configure the model to save the relation to the database and be able to refer to it in the view.
Please help.
My models code:
class Model_Task extends ORM
{
protected $_table_name = 'task';
protected $_table_columns = array(
'id'=>array('data_type'=>'int','is_nullable'=>false),
'date' => array('data_type'=>'date','is_nullable'=>
'description'=>array('data_type'=>'varchar','is_nullable'=>true)
);
protected $_belongs_to = array(
'task_type_id' => array(
'model' => 'TaskType',
'foreign_key' => 'id'
)
);
}
class Model_TaskType extends ORM
{
protected $_table_name = 'task_type';
protected $_table_columns = array(
'id'=>array('data_type'=>'int','is_nullable'=>false),
'name' => array('data_type'=>'string','is_nullable'=>false)
);
}
Probably it should be:
class Model_Task extends ORM
{
protected $_table_name = 'task';
protected $_table_columns = array(
'id'=>array('data_type'=>'int','is_nullable'=>false),
'date' => array('data_type'=>'date','is_nullable'=>
'description'=>array('data_type'=>'varchar','is_nullable'=>true),
'task_type_id' => array('data_type'=>'int','is_nullable'=>false),
);
protected $_belongs_to = array(
'task_type' => array(
'model' => 'TaskType',
'foreign_key' => 'id'
)
);
}
class Model_TaskType extends ORM
{
protected $_table_name = 'task_type';
protected $_table_columns = array(
'id'=>array('data_type'=>'int','is_nullable'=>false),
'name' => array('data_type'=>'string','is_nullable'=>false)
);
}
and adding by $task->add('task_type', $task_type);

Why do my models return 0 when accessing a string-based primary key model property in Laravel 4?

I have a table set up something like this:
Schema::create('capability', function($T) {
$T->string('code',32)->primary();
$T->string('name',64);
});
And a corresponding model like this:
class Capability extends BaseModel {
protected $table = 'capability';
protected $primaryKey = 'code';
public $timestamps = false;
}
When I seed some data like this...
$c1 = Capability::create(array(
'name' => 'Manage Clients',
'code' => 'manage_clients'
));
...and access the data members of $c1 like this...
echo $c1->name.", ".$c1->code;
...the result is Manage Clients, 0.
Why is the result not Manage Clients, manage_clients as I was expecting?
I needed to add public $incrementing = false to the model class.

Resources