Illuminate\Database\QueryException in Laravel 6.0 but not in 5.8 - laravel-6

I am having a problem with Laravel 6.0. The same source code is running ok with Laravel 5.8. The error is the following:
Illuminate\Database\QueryException
SQLSTATE[22018]: [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Conversion failed when converting the nvarchar value 'XXXX' to data type int. (SQL: select * from [business_units] where [business_units].[code] in (0, 0, 0, 0))
Tried to create laravel project both using 5.8 and 6.0 containing the same source code but result is the same, running good in 5.8 but not in 6.0. Probably there is something wrong in Eloquent.
Here is the migration:
Schema::create('cost_centers', function (Blueprint $table) {
$table->string('code', 6)->primary();
$table->string('descr', 50);
$table->string('business_unit_code', 6)->index();
$table->foreign('business_unit_code')->references('code')->on('business_units');
$table->timestamps();
});
My Model script is:
class CostCenter extends Model
{
protected $primaryKey = 'code';
protected $fillable = ['code', 'descr', 'business_unit_code'];
public $incrementing = false;
public function businessUnit()
{
return $this->belongsTo(BusinessUnit::class);
}
}
This is after opening a form with the column in the table referencing another column where primary key is String. Did anybody encounter this problem, what is your resolution?

In the table model "business_units", I change the declaration from
This is necessary when using string as primary key.
public $incrementing = false;
to
protected $keyType = 'string';
This is specify in the Laravel upgrade guide as pointed to me by Sinnbeck of Laracast but somehow missed it.
https://laravel.com/docs/6.x/upgrade#eloquent-primary-key-type

Related

Column does not exist Laravel Factory

I have a table
public function up()
{
Schema::create('parties', function (Blueprint $table) {
$table->id();
$table->integer('place_id');
$table->tinyInteger('status')->default(0);
$table->dateTime('utc_date');
$table->dateTime('local_date');
$table->timestamps();
});
Schema::table('parties', function (Blueprint $table) {
$table->index('place_id');
$table->foreign('place_id')
->references('id')
->on('places')
->onDelete('restrict');
});
}
and model factory
<?php
/** #var \Illuminate\Database\Eloquent\Factory $factory */
use App\Models\Party;
use Faker\Generator as Faker;
$factory->define(Party::class, function (Faker $faker) {
$date = $faker->dateTimeBetween(now()->subDays(3), now());
return [
'place_id' => $faker->numberBetween(1, 9),
'status' => $faker->numberBetween(0, 3),
'utc_date' => $date,
'local_date' => \Carbon\Carbon::make($date)->addHours(3),
];
});
If i call the method create in HomeController it works correctly
factory(Party::class, 10)->create();
but when i call it in my tests I got an error
SQLSTATE[42703]: Undefined column: 7 ERROR: column "utc_date" of
relation "parties" does not exist LINE 1: insert into "parties"
("place_id", "status", "utc_date", "lo...
^ (SQL: insert into "parties" ("place_id", "status", "utc_date", "local_date",
"updated_at", "created_at") values (5, 3, 2020-08-04 00:34:52,
2020-08-04 03:34:52, 2020-08-04 11:42:18, 2020-08-04 11:42:18)
returning "id")
<?php
namespace Tests\Feature\API;
use App\User;
use Tests\TestCase;
use Laravel\Sanctum\Sanctum;
use App\Models\{Party, Place};
use Illuminate\Foundation\Testing\RefreshDatabase;
class PartiesControllerTest extends TestCase
{
use RefreshDatabase;
private User $user;
protected function setUp(): void
{
parent::setUp();
$this->user = factory(User::class)->create();
}
public function test_get_parties()
{
factory(Party::class)->create([
'place_id' => factory(Place::class)->create()->id,
]);
dd(Party::all());
Sanctum::actingAs($this->user);
}
}
I am using second database for testing. I connected to this db and found that this table has not been refreshed. I don't know why because I used RefreshDatabase trait. I added this field manually for solving this problem.
Try to run php artisan migrate:fresh. If you use another database for testing and using another .env file then try to run php artisan migrate:fresh --env=testing.
For example: you can use file env.testing and APP_ENV=testing inside this file.
Maybe you added this field later and did not refresh DB. Also, check if the field exists in visual DB.
If it didn't help try to run composer dump-autoload and retry.
please make sure the fillable array in model has this key,
and try using carbon instead of faker with date
(Carbon::now())->subDays(3);

Table not found exception using javalite

So I have a very simple table I made in SQL using h2
CREATE TABLE USERS(
username varchar(255) NOT NULL,
password varchar(255),
);
I'm trying to use javalite to add an entry to it so I made this following the instructions on the site.
package DBTEST;
import org.javalite.activejdbc.Base;
public class makeDB {
public static void main(String[] args) {
Base.open("org.h2.Driver", "jdbc:h2:./test", "sa", "");
User e = new User();
e.set("username", "John");
e.set("password", "Doe");
e.saveIt();
User.findAll().dump();
Base.close();
}
}
I have a class Users for this table
package DBTEST;
import org.javalite.activejdbc.Model;
import org.javalite.activejdbc.annotations.Table;
#Table("USERS")
public class User extends Model {
}
I keep getting this exception
Exception in thread "main" org.javalite.activejdbc.DBException: org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "USERS" not found; SQL statement:
Can anyone help? I have no idea why this is happening
First, your SQL has an extra comma in "CREATE USERS" statement. The errors says: "able "USERS" not found" - this mean you simply do not have a table!
Second, the table definition is missing an id, please see https://javalite.io/surrogate_primary_keys
Third, I created a simple example project and added your code there. It is working as expected. The project can be found here: https://github.com/javalite/h2-example
The output from running this program looks like this:
Model: activejdbc.examples.simple.User, table: 'users', attributes: {ID=1, PASSWORD=Doe, USERNAME=John}
which is exactly as expected.
Additionally, the #Table annotation is not necessary: https://javalite.io/english_inflections

Laravel seed table from multiple csv files

I'm very new to Laravel and Database and I'm trying to understand how to insert data into my database. Please be patient the question can sounds dummy for you.
STEP
I created a table in migrations. Example of a table:
public function up(){
Schema::create('job-urls', function (Blueprint $table) {
$table->increments('id');
$table->foreign('job_id')->references('id')->on('jobs');
$table->string('url')->index();
$table->string('hash');
$table->timestamp('created_at')->nullable();
$table->timestamp('updated_at')->nullable();
STEP
I have two csv file that correspond to the field url and hash and I want to insert them. I created a new file in migration called populate_jobs_url
class PopulateJoburls extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up(){
$fileurls = fopen('../data/urls.csv', 'r');
$filehash = fopen('../data/urls_hash.csv', 'r');
while (($row = fgetcsv($fileurls, 0, ',')) !=FALSE){
DB::table('joburls')->insert(
array(
'url' => $row,
)
);
}
while (($row = fgetcsv($filehash, 0, ',')) !=FALSE){
DB::table('joburls')->insert(
array(
'hash' => $row,
)
);
}
}
Can you help me to understand how I check if the table is correctly filled? Is this approach correct? How could I insert data otherwise in my Database? Unfortunately all examples on the web deal with inserting manually data with a form.
Thanks
Seeding the table inside of a migration file is not the best practise. You can take advantage of Seeders, which is right way to fill your table with test or actual data.
First, create a seeder file with php artisan make:seeder PopulateJobUrls command. Then you can arrange your seeder like this:
<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class PopulateJobUrls extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$fileurls = fopen('../data/urls.csv', 'r');
$filehash = fopen('../data/urls_hash.csv', 'r');
// Rest of your seeding logic...
}
}
You should reference your seeder from database/seeds/DatabaseSeeder.php in the run method:
$this->call(PopulateJobUrls::class);
Run php artisan db:seed or if you want to be more specific, php artisan db:seed --class=PopulateJobUrls and you are good to go with your correctly filled data!

how to seed in Yii?

I'm wondering how one can seed in Yii a table once it is created with migration?
I've got a migration with an up-method:
public function up()
{
$this->createTable('users',array('id'=>"pk",
'login'=>'string NOT NULL'));
echo "table 'users' is created.\n";
return true;
}
I've got as well corresponding Users model and its CRUD actions. When I try to execute another migration with an up-method
public function up()
{
$user = new Users;
$user->login = "Bob";
return $user->save();
}
I get the following error:
PHP Error[2]: include(users.php): failed to open stream: No such file or directory
in file MyYiiRoot\yii\framework\YiiBase.php at line 421
I've managed to achieve the desired result by using query builder (by means of insert command), but I hope there is a nicer way out.
Use
public function safeUp()
{
$this->insert('users',array(
'login'=>'Bob'));
}
You can also do update, delete and a host of other actions. Look at http://www.yiiframework.com/doc/api/1.1/CDbMigration for more information

Cannot instantiate a Zend_Table in Zend Framework

I'm using Zend Framework version 1.7.8.
I am trying to create a class that extends from Zend_Db_Table_Abstract:
class My_Model_Table extends Zend_Db_Table_Abstract {
public function __construct($tableName) {
parent::__construct(array('name' => $tableName, 'primary' => 'dummy', 'db' => Zend_Registry::get('dbAdapter')));
}
}
However, when I try to fetch from this table:
$table = new My_Model_Table('dual');
Zend_Debug::dump($table->fetchAll());
I am getting this exception:
Primary key column(s) (dummy) are not columns in this table (DUMMY)
For those of you not familiar with Oracle, the DUAL table is a standard Oracle table which has only one column: DUMMY. From what I can see in the error message, ZF is trying to fetch from the "DUMMY" table which doesn't exist. Am I right? What am I doing wrong?
Thanks!
Have you tried:
Class VCCE_Model_Table extends Zend_Db_Table_Abstract {
protected $_name = 'DUAL';
}
$table = new VCCE_Model_Table();
Zend_Debug::dump($table->fetchAll());
Note: in your example you use two different names for your table VCCE_Model_Table and My_Model_Table.
Did you check the configuration settings for dbAdapter?