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

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.

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;
}

Create table with custom name dynamically and insert with custom table name

I want to create the table with custom name but I cannot find the sample code. I notice the only way to create table is by generic type like db.CreateTable(). May I know if there is a way to create the table name dynamically instead of using Alias? The reason is because sometime we want to store the same object type into different tables like 2015_january_activity, 2015_february_activity.
Apart from this, the db.Insert also very limited to object type. Is there anyway to insert by passing in the table name?
I think these features are very important as it exists in NoSQL solution for long and it's very flexible. Thanks.
OrmLite is primarily a code-first ORM which uses typed POCO's to create and query the schema of matching RDMBS tables. It also supports executing Custom SQL using the Custom SQL API's.
One option to use a different table name is to change the Alias at runtime as seen in this previous answer where you can create custom extension methods to modify the name of the table, e.g:
public static class GenericTableExtensions
{
static object ExecWithAlias<T>(string table, Func<object> fn)
{
var modelDef = typeof(T).GetModelMetadata();
lock (modelDef) {
var hold = modelDef.Alias;
try {
modelDef.Alias = table;
return fn();
}
finally {
modelDef.Alias = hold;
}
}
}
public static void DropAndCreateTable<T>(this IDbConnection db, string table) {
ExecWithAlias<T>(table, () => { db.DropAndCreateTable<T>(); return null; });
}
public static long Insert<T>(this IDbConnection db, string table, T obj, bool selectIdentity = false) {
return (long)ExecWithAlias<T>(table, () => db.Insert(obj, selectIdentity));
}
public static List<T> Select<T>(this IDbConnection db, string table, Func<SqlExpression<T>, SqlExpression<T>> expression) {
return (List<T>)ExecWithAlias<T>(table, () => db.Select(expression));
}
public static int Update<T>(this IDbConnection db, string table, T item, Expression<Func<T, bool>> where) {
return (int)ExecWithAlias<T>(table, () => db.Update(item, where));
}
}
These extension methods provide additional API's that let you change the name of the table used, e.g:
var tableName = "TableA"'
db.DropAndCreateTable<GenericEntity>(tableName);
db.Insert(tableName, new GenericEntity { Id = 1, ColumnA = "A" });
var rows = db.Select<GenericEntity>(tableName, q =>
q.Where(x => x.ColumnA == "A"));
rows.PrintDump();
db.Update(tableName, new GenericEntity { ColumnA = "B" },
where: q => q.ColumnA == "A");
rows = db.Select<GenericEntity>(tableName, q =>
q.Where(x => x.ColumnA == "B"));
rows.PrintDump();
This example is also available in the GenericTableExpressions.cs integration test.

Create content error - Specified cast is not valid

I have a custom module. Migrations.cs looks like this.
public int Create()
{
SchemaBuilder.CreateTable("MyModuleRecord", table => table
.ContentPartRecord()
...
);
ContentDefinitionManager.AlterPartDefinition(
typeof(MyModulePart).Name, cfg => cfg.Attachable());
ContentDefinitionManager.AlterTypeDefinition("MyModule",
cfg => cfg
.WithPart("MyModulePart")
.WithPart("CommonPart")
.Creatable()
);
return 1;
}
This is the code I have in the controller.
var newcontent = _orchardServices.ContentManager.New<MyModulePart>("MyModule");
...
_orchardServices.ContentManager.Create(newcontent);
I get the invalid cast error from this New method in Orchard.ContentManagement ContentCreateExtensions.
public static T New<T>(this IContentManager manager, string contentType) where T : class, IContent {
var contentItem = manager.New(contentType);
if (contentItem == null)
return null;
var part = contentItem.Get<T>();
if (part == null)
throw new InvalidCastException();
return part;
}
Any idea what I am doing wrong?
Thanks.
This is the handler.
public class MyModuleHandler : ContentHandler
{
public MyModuleHandler(IRepository<MyModuleRecord> repository)
{
Filters.Add(StorageFilter.For(repository));
}
}
You are getting the InvalidCastException because the content item doesn't appear to have your MyModulePart attached.
If there were a driver for your part, then there is an implicit link somewhere that allows your part to be shown on a content item (I'm not sure how this is done, maybe someone else could elaborate - but it is something to do with how shapes are harvested and picked up by the shape table deep down in Orchard's core).
However since you don't have a driver, adding an ActivatingFilter to your part's handler class will make the link explicitly:
public MyModulePartHandler : ContentHandler {
public MyModulePartHandler() {
Filters.Add(StorageFilter.For(repository));
Filters.Add(new ActivatingFilter<MyModulePart>("MyModule");
}
}
Your part table name is wrong. Try renaming it to this (so the part before "Record" matches your part model name exactly):
SchemaBuilder.CreateTable("MyModulePartRecord", table => table
.ContentPartRecord()
...
);

Subsonic 3, how to CRUD using LinqTemplates?

I am new to Subsonic, and it seems that I cant find out a natural way to do CRUD operations using the LINQ template classes. I guess in ActiveRecord, you could:
Product p = new Product();
p.ProductCode = "xxx";
p.Add();
Using the LINQTemplate generated classes however, how can I do the same thing? I can only use something like this below to insert a product object:
db.Insert.Into<UnleashedSaaS.PRODUCT>(prod => prod.Code, prod => prod.Description).Values("Product1", "Product1 Desc").Execute();
Who could kindly give me some hints? I'd really appreciate it.
All the CRUD happens in SubSonicRepository, which you can derive from. For example, I would have a class like this:
public class ProductRepository : SubSonicRepository<Product> {
public ProductRepository() : base(new NorthwindDB()) { }
// need this here because base doesn't expose the DB class that I know of
protected NorthwindDB _db;
protected NorthwindDB DB {
get {
if (_db == null) _db = new NorthwindDB();
return _db;
}
}
public void Save(Product product) {
if (product.ProductId == 0) {
Add(product); // Add is part of SubSonicRepository
} else {
Update(product);
}
}
public void Delete(Product product) { ... }
public List<Product> ListAll() {
var products = from p in DB.Products
select p;
return products.ToList();
}
public Product GetById(int id) {
return DB.GetByKey(id);
}
}
And so on. It's nice because you can consolidate all your data access methods in one place. If you have Sprocs, they're generated as methods on DB as well.
When I get time I'm going to work on adding a Save method to SubSonicRepository directly so you don't have to do the check yourself to see which method (Add or Update) to call.
I have modified the Classes.tt file to include:
public partial class <#=tbl.ClassName#>Repository : SubSonicRepository<<#=tbl.ClassName#>>
{
public <#=tbl.ClassName#>Repository() : base(new <#=DatabaseName#>DB()) { }
}
Insert that bunch of lines between
<# foreach(Table tbl in tables){#>
and
/// <summary>
right at the top, near the namespace declaration, in my file it can be inserted in line 18.
The last thing to do is to add another "using" statement, in line 10, the next line after System.Linq statement. Now it should look like:
using System.Linq;
using SubSonic.Repository;
That will generate a repository to give you access to basic functionality, but can be modified in another partial class.
Hope that helps.

Resources