Table creaction on doctrine migration for custom behavior - doctrine

I've created custom doctrine(1.2) behavior which should create tables for models (very simmilar to i18n behavior). I see this tables in schema.sql, and if i execute it everything is fine, but this is no such tables if my migrations diff (doctrine:generate-migrations-diff).
What i'm doing wrong?
class DescriptionableGenerator extends Doctrine_Record_Generator
{
protected $_options = array(
'className' => '%CLASS%Description',
'tableName' => '%TABLE%_description',
'fields' => array(),
'generateFiles' => false,
'table' => false,
'pluginTable' => false,
'children' => array(),
'options' => array(),
'cascadeDelete' => true,
'appLevelDelete' => false
);
public function __construct(array $options = array())
{
$this->_options = Doctrine_Lib::arrayDeepMerge($this->_options, $options);
}
public function buildRelation()
{
$this->buildForeignRelation('Descriptions');
$this->buildLocalRelation();
}
public function setTableDefinition()
{
$this->hasColumn('lang', 'char', '2', array('notnull' => true));
$this->hasColumn('field', 'string', '255', array('notnull' => true));
$this->hasColumn('title', 'string', '255', array('notnull' => true));
$this->hasColumn('description', 'clob');
$this->hasColumn('compulsory', 'boolean', 1, array('notnull' => true, 'default' => 0));
$this->addListener(new DescriptionableListener());
}
}

Solved!
Problem appears due to command "php symfony doctrine:build-model".
So, if you have the same problem you should:
Remove your behavior from schema.
Execute "php symfony doctrine:build-model".
Add your behavior to schema.
Run "php symfony doctrine:generate-migrations-diff".
Chears! %)

Related

Laravel-Auditing is not working without any errors

I've recently installed this package and configured everything with guide but some how it's not working!
By it's not working I mean it's not adding anything to database. I really don't know what is wrong with my configs but I've checked everything with guide 3 times and everything is correct but... I don't know
config/audit.php:
<?php
return [
'enabled' => env('AUDITING_ENABLED', true),
'implementation' => OwenIt\Auditing\Models\Audit::class,
'user' => [
'morph_prefix' => 'user',
'guards' => [
'web',
'api',
],
],
'resolver' => [
'user' => OwenIt\Auditing\Resolvers\UserResolver::class,
'ip_address' => OwenIt\Auditing\Resolvers\IpAddressResolver::class,
'user_agent' => OwenIt\Auditing\Resolvers\UserAgentResolver::class,
'url' => OwenIt\Auditing\Resolvers\UrlResolver::class,
],
'events' => [
'created',
'updated',
'deleted',
'restored',
'gold_mailed' => 'goldMailed',
'invited' => 'clientInvited',
],
'strict' => false,
'timestamps' => false,
'threshold' => 0,
'driver' => 'session',
'drivers' => [
'eloquent' => [
'table' => 'audits',
'connection' => null,
],
],
'console' => true,
];
My model that I want to audit:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use OwenIt\Auditing\Contracts\Auditable;
use App\Models\Expansion;
use App\Models\Audit;
class Setting extends Model implements Auditable
{
protected $table = 'settings';
use \OwenIt\Auditing\Auditable;
protected $fillable = [
'expansion_id', 'season', 'advertiser_app', 'pvp_app', 'raid_app', 'version'
];
protected $auditInclude = [
'expansion_id', 'season', 'advertiser_app', 'pvp_app', 'raid_app', 'version'
];
public function Expansion()
{
return $this->hasOne(Expansion::class, 'id', 'expansion_id');
}
}
web.php:
Route::post('/setting' , 'Admin\SuperAdminController#saveSetting')->middleware('superadmin')->name('admin_save_setting');
Controller:
public function saveSetting(Request $request)
{
$sql = Setting::where('id', 1)->update([
'expansion_id' => $request['expansion_id'],
'season' => $request['season'],
'advertiser_app' => $request['advertiser_app'],
'pvp_app' => $request['pvp_app'],
'raid_app' => $request['raid_app'],
'version' => $request['version']
]);
if ($sql) {
toastr()->success('Settings successfully updated.');
return redirect()->back();
}
toastr()->error('Something went wrong!');
return redirect()->back();
}
I don't know what infos do you need but I think this is enough
I think my problem is with "driver" in config file , I don't know if that's correct or not
[UPDATED]
Based on the controller code you showed, it didn't work because your code is being called using Builder style, and the package only works when it is called using Eloquent style.
Documentation link
So, maybe you need to change your code to:
$setting = Setting::where('id', 1)->firstOrFail();
$setting->update([
'expansion_id' => $request['expansion_id'],
'season' => $request['season'],
'advertiser_app' => $request['advertiser_app'],
'pvp_app' => $request['pvp_app'],
'raid_app' => $request['raid_app'],
'version' => $request['version']
]);
now I have another problem -_-
this is my controller:
$sql = Raid::findOrFail($request['id']);
$sql = $sql->update($request->all());
I have a array in my table , after update value will be like this:
"{\"Plate\":0,\"Cloth\":0,\"Mail\":0,\"Leather\":0}"
but it should be:
{"Plate":"0","Cloth":"0","Mail":"0","Leather":"0"}
so I will get an error
before this , I was updating like this and it was ok:
$sql = Raid::where('id', $request['id'])->update($request->all());
and this is my mode (traders and class_traders is fields that I have problem with):
use SoftDeletes;
use \OwenIt\Auditing\Auditable;
protected $table = 'raid';
protected $dates = ['date_and_time','deleted_at'];
protected $fillable = [
'admin_id', '....
];
protected $casts = [
'bosses' => 'array',
'traders' => 'array',
'class_traders' => 'array',
'boosters' => 'array',
];

Form validation in Codeigniter 3 using different database

I got in trouble with Codeigniter 3 using the form validation library; I have to check that the email address submitted by a user into aregistration form is unique into the users database.
I use two databases in my project, the users one is not the default.
To perform the email check I use the following code:
$this->form_validation->set_rules('email','Email','trim|required|valid_email|is_unique[users.email]');
I got an error about the missing users table into the default database, so I've realized that CI 3 looks the email to check into a default database ... not the correct users database, even if in the construct I load the correct model/database.
Is there a way to perform the check into a different database using the form validation above?
Thanks for any feedback
UPDATE
Below the code I use to load the model in the controller
function __construct()
{
parent::__construct();
$this->load->model("admin/user_model","user");
}
Below the code of the User_model
// Database
private $auth_db;
// Tables
private $table_users = 'users';
public function __construct()
{
parent::__construct();
$this->auth_db = $this->load->database('auth', true);
}
and...finally...in the config file the database configuration
$active_group = 'default';
$query_builder = TRUE;
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'xxxxxxxxx',
'password' => 'xxxxxxxxx',
'database' => 'vfr_main',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => TRUE,
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_unicode_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
$db['auth'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'xxxxxxxxxxx',
'password' => 'xxxxxxxxxxx',
'database' => 'vfr_auth',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => TRUE,
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_unicode_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
In CodeIgniter 3, models do not have a direct way to control which database group they connect to. In this case I do not think we can simply write a custom validation rule, because is_unique is the only rule that makes a db call, and there is no built in way to change db.
In this case I think the most direct approach would be to extend the form validation class, and then add a new is_unique_authdb method in this extended library for checking with the second db. Then you would use this new method in place of the call you have shown above.
In the 3.x repo on git hub I see this is the existing method.
public function is_unique($str, $field)
{
sscanf($field, '%[^.].%[^.]', $table, $field);
return isset($this->CI->db)
? ($this->CI->db->limit(1)->get_where($table, array($field => $str))->num_rows() === 0)
: FALSE;
}
And your extra method could be something like:
public function is_unique_authdb($str, $field)
{
$db = $this->CI->load->database('auth', true);
sscanf($field, '%[^.].%[^.]', $table, $field);
return isset($db)
? ($db->limit(1)->get_where($table, array($field => $str))->num_rows() === 0)
: FALSE;
}
Extending a native library is very simple. For example, to extend the native Form_validation class you’ll create a file named application/libraries/MY_Form_validation.php, and declare your class with:
class MY_Form_validation extends CI_Form_validation {
public function is_unique_authdb($str, $field)
{
$db = $this->CI->load->database('auth', true);
sscanf($field, '%[^.].%[^.]', $table, $field);
return isset($db)
? ($db->limit(1)->get_where($table, array($field => $str))->num_rows() === 0)
: FALSE;
}
}
Then you would load the library as normal but it will load your extended library and you can use the authdb method for this validation.
$this->form_validation->set_rules('email','Email','trim|required|valid_email|is_unique_authdb[users.email]');
CI3 docs for extending a native library.
Note: With CodeIgniter 4 I think this would be more simple because CI4 has a built in property for models that specifically allows you to manage which db a model will connect to.

Infinityfree.net and codeigniter

Good Day!
I have this problem using infinityfree.net as my hosting site.
I used codeigniter framework for my code.
The problem is:
An uncaught Exception was encountered
Type: RuntimeException
Message: Unable to locate the model you have specified: Login_model
My code working properly on xampp.
database.php
$active_group = 'default';
$query_builder = TRUE;
$db['default'] = array(
'dsn' => '',
'hostname' => 'HOSTNAME',
'username' => 'USERNAME',
'password' => 'PASSWORD',
'database' => 'DATABASE_NAME',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
Here's my login_model.php
class Login_model extends CI_Model{
public function __construct()
{
parent::__construct();
}
function login($par1,$par2){
//CODE HERE
}
Here's my controller
class Login extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('form_validation');
$this->load->helper('url', 'form');
}
public function login()
{
$this->load->model('login_model');
}
PS. i didnt include much more code in controller because thats the only thing that has error and also Im unable to post too much code because of the rule of stackoverflow. Hoping you guys to help me. Thanks in advance
Fixed
I just renamed my login_model to Login_model

Init a second database in codeigniter by a helper function

In my site are different modules, each has its own datatable.
So now I'm not sure which is the best way to connect these modules in the best way.
My idea is to create a helper function, which tests if is a database-connection is available or not. If not, the helper should init the database and make the database for queries available in the controller and models.
In the documentation of Codeigniter I've only found information about multiple database setup - I cannot find an example for do that with a kind of dynamic helper.
Maybe someone can help me a step further?
What you can do is set session of your db_name, db_user and db_pass (if user and pass are different for each db_name). In order to reuse the dynamic db without always passing the access.
Here is an implementation:
Helper:
if (!function_exists('get_dynamic_db')){
function get_dynamic_db()
{
$CI =& get_instance();
$db = $CI->session->user_data('other_db');
$user = $CI->session->user_data('other_db_user');
$pass = $CI->session->user_data('other_db_pass');
$config_app = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => $user,
'password' => $pass,
'database' => $db,
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
return $CI->load->database($config_app,TRUE);
}
}
Model:
Class DD_model extends CI_Model {
var $dynamic_db;
public function __construct() {
$this->load->database(); // default db
$this->dynamic_db = get_dynamic_db(); // dynamic db
}
public function ping_server_db()
{
$this->dynamic_db->from('some_table');
$query = $dynamic_db->get();
return $query->row() ? true : false;
}
}
Controller:
public function select_db($db_name)
{
$this->session->set_userdata(array('other_db' => $db_name, 'other_db_user' => 'user', 'other_db_pass' => 'pass'));
$dynamic_db = $this->DD_model->ping_server_db();
if (!$dynamic_db) {
$this->session->unset_userdata('other_db');
return false;
}
}
With this, you can then use get_dynamic_db(); in all your models to query from dynamic db

A simple innerJoin Doctrine Query

I tried to generate a simple SQL select:
SELECT c.com_id, c.pro_id, c.com_nombre
FROM bd_fn.fn_comuna c
inner join bd_fn.fn_provincia p
on (c.pro_id = p.pro_id)
where p.pro_nombre = 'namepro';
But the DQL throw this error:
Doctrine_Table_Exception' with message 'Unknown relation alias fn_provincia.
The doctrine version is 1.XX, the persistence was create by Visual Paradigm.
The DQL is this:
$q = Doctrine_Query::create()
->select('c.com_id')
->from('fn_comuna c')
->innerJoin('c.fn_provincia p')
->where('p.pro_nombre=?',$namepro);
the class fn_comuna.php
<?php
/**
* "Visual Paradigm: DO NOT MODIFY THIS FILE!"
*
* This is an automatic generated file. It will be regenerated every time
* you generate persistence class.
*
* Modifying its content may cause the program not work, or your work may lost.
*/
class Fn_comuna extends Doctrine_Record {
public function setTableDefinition() {
$this->setTableName('bd_fn.fn_comuna');
$this->hasColumn('com_id', 'integer', 4, array(
'type' => 'integer',
'length' => 4,
'unsigned' => false,
'notnull' => true,
'primary' => true,
'autoincrement' => false,
)
);
$this->hasColumn('pro_id', 'integer', 4, array(
'type' => 'integer',
'length' => 4,
'unsigned' => false,
'notnull' => true,
)
);
$this->hasColumn('com_nombre', 'string', 100, array(
'type' => 'string',
'length' => 100,
'fixed' => false,
'notnull' => true,
)
);
}
public function setUp() {
parent::setUp();
$this->hasOne('Fn_provincia as pro', array(
'local' => 'pro_id',
'foreign' => 'pro_id'
)
);
$this->hasMany('Fn_institucion as fn_institucion', array(
'local' => 'com_id',
'foreign' => 'com_id'
)
);
$this->hasMany('Fn_replegal as fn_replegal', array(
'local' => 'com_id',
'foreign' => 'com_id'
)
);
}
}
?>
As you can see from your model class, the relation between fn_comuna & fn_provincia is called pro.
$this->hasOne('Fn_provincia as pro', array(
'local' => 'pro_id',
'foreign' => 'pro_id'
)
);
So you have to use this name when you deal with join:
$q = Doctrine_Query::create()
->select('c.com_id')
->from('fn_comuna c')
->innerJoin('c.pro p')
->where('p.pro_nombre=?', $namepro);
Change:
p.pro_id = (SELECT p2.pro_id FROM etc..
To:
p.pro_id IN(SELECT p2.pro_id FROM etc..
Not sure why you need the subquery in the first place, why not just loose it and replace it with:
where pro_nombre = 'namepro'

Resources