I need to start primary_key index from e.g. 1000. How can I do it in migration? Or maybe in a model (but as I understand yii2 doesn't know anything about what id row will have)?
I found a solution:
create a new migration and in up function add:
public function safeUp()
{
$this->execute("ALTER TABLE {table_name} AUTO_INCREMENT = 1000;");
}
Related
If I have a table called Master Index which has for example : Country Name = " USA ", and I want to have several models linked to it (GDP,Population,Inequality,etc) , how do I define that list of models in a field so that I can know which properties does that Country has?
Let me know if its possible, thanks!
You can read HERE
First you need to create table but make it in migration that the table you will create is base on the hierarchy example:
If you have Master Index as your general root of relationship young need to make it first in the migration. It will look like this on your Database > Migrations folder.
2020_07_14_0000001_create_master_indexs_table.php
2020_07_14_0000001_create_gdps_table.php
2020_07_14_0000001_create_populations_table.php
2020_07_14_0000001_create_inequalities_table.php
Master Index Model
You will specify the relationship it should look like this:
public function gdps() {
return $this->hasMany(Gdp::class); // if you have different foreign key you can specify it in the next argument return [$this->hasMany(Gdp::class, 'gdp_id');] like this
}
public function populations() {
return $this->hasMany(Population::class);
}
public function inequalities() {
return $this->hasMany(Inequality::class);
}
GDPS Model / Populations Model / Inequality Model
You need to specify where it belongs. It should be like this.
public function master_index() {
return $this->belongsTo(MasterIndex::class);
}
GDPS Migration / Population Migration / Inequality Migration
In your migration you should specify the foreign key.
If you're using Laravel 7.x you can do like this.
$table->foreignId('master_index_id')->constrained()->cascadeOnDelete();
If you're not familiar with the above code you can do also like this:
$table->unsignedBigInteger('master_index_id');
$table->foreign('master_index_id')->references('id')->on('master_indexs')->onDelete('cascade');
I want to create a settings table with 2 columns (Setting, value) and setting will hold something like SITE_NAME and Value will be the value like "Facebook" or "Youtube" or something like that. This will hold the site name, logo url and etc. How would i create this and most importantly how would i fetch the info with Laravel eloquent without a id field.
First things first.
Your table requires a primary key. Will that be a varchar field, according to your example? MySql's search by name is WAY SLOWER than comparing an with an index (integer). What it does in theory (google can explain it better) is somewhat converting text to an index and validating it, whereas with an index it just accesses it. I see nothing wrong - infact, I support - the idea of having an id column as a primary key. If duplicates is your worry, then you can set unique on your column site_name.
Create a migration to create a table
php artisan make:migration settings_table
Fill your migration code
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class SettingsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('settings', function (Blueprint $table) {
//$table->increments('id'); This will come in hand, trust me
$table->string('site_name',255)->unique();
//If you really insist on having site_name as primary key, then use the line below
// $table->string('site_name',255)->primary();
$table->string('value',255);
//$table->timestamps(); Do you need?
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('settings');
}
}
Create a Eloquent model
php artisan make:model Setting
Fill your Eloquent model
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Setting extends Model
{
protected $fillable = ['site_name','value'];
//protected $table = ['settings'] Only if you really need it
//Usually, if you take Laravel's approach, Models are singular version of the tables, that are in plural, but you can work it as you like
}
is there a way to make a laravel trigger for this sql command? sorry I am new to laravel and having a hard time figuring it out.
So what should happen is when the table.a get its content, it will automactically fill the column with ids from the other table. is it possible for laravel? Thank you so much.
UPDATE table_a
INNER JOIN table.b ON table_a.account_code =
table.ac_code
SET table_a.ut_id = table.ut_id, table_a.pj_id
= table.pj_id
I used to use laravel event for trigger stuff in laravel (it assumes you have models on this). In your to be listened Model_B (table_b), you can define something like :
public function boot()
{
parent::boot();
static::created(function ($model) {
/*update table a here*/
$ut_id = $model->ut_id;
$pj_id = $model->pj_id;
Table_A::customUpdate($ut_id, $pj_id);
});
}
Please define your public customUpdate( ) as you want.
Check laravel doc above to see other possibilities for boot methods: creating, created, updating, updated, saving, saved, deleting, deleted, restoring, restored
I have a few tables where I need tinyint fields which have to be unsigned and set to auto_increment.
The L5.3 Database : Migrations documentation does not have a method to define unsigned auto-incrementing tinyint.
I have tried to implement it using the DB::update(). My migration file for the table looks like:
public function up()
{
Schema::create('table_name', function (Blueprint $table)
{
$table->unsignedTinyInteger('field1');
$table->string('field2', 255);
$table->primary('field1');
$table->index('field2');
$field = "field1";
});
$this->addAutoIncrements($field);
}
public function addAutoIncrements($field)
{
DB::update('ALTER TABLE table_name MODIFY $field TINYINT UNSIGNED NOT NULL AUTO_INCREMENT');
}
When I try php artisan migrate with such a migration file, it migrates without any errors but is not assigning auto-increment.
How do I resolved this? Should I do the update as a complete new migration? Has anyone done it before?
The second parameter for the unsignedTinyInteger() method is a boolean to flag if it is an autoincrementing field. It defaults to false, so you just need to update your migration to pass in true.
$table->unsignedTinyInteger('field1', true);
As a future note, the tinyIncrements() convenience method was added in Laravel 5.4.16 to do exactly that.
I have a cakePHP problem - I want to make a update query like this
UPDATE table SET field = field + some_var
and I don't know how to do it...
Can anyone help me?
The only "right" way would be using cake's "atomic query" wrapper methods. In your case that would be "updateAll".
The question is a complete duplicate of a dozen other questions - like Incrementing Cakephp database field by a value
$var = 1;
$this->Article->updateAll(
array('Article.viewed' => 'Article.viewed + ' . $var),
array('Article.id' => $id)
);
This is also in the docs: http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-updateall-array-fields-array-conditions
There are two ways to do an update:
If you are only updating one field you can do:
$this->Model->id = foo;
$this->Model->saveField('field_name', 'field_value');
or, you can do an update using $this->Model->save():
$data = array(
'Model'=>array(
'id'=>foo,
'field_name'=>'field_value',
'another_field_name'=>'another_field_value'
)
);
$this->Model->save($data);
You want to avoid using $this->Model->query() and use CakePHP's built in methods because the build in methods are datasource agnostic (they work the same on MySQL, Oracle, MSSQL etc.)
You can use the callback method beforeSave to implement what you need.
Callback Method: BeforeSave
public function beforeSave($options = array()) {
if (!empty($this->data['table']['field'])){
$this->data['table']['field'] += $this->data['table']['some_var'];
}
return true;
}
I think the best method is using the Model::updateAll(array $fields, array $conditions).
The Model::saveField(string $fieldName, string $fieldValue, $validate = false) this method when you try to update using same primary key it shows cannot replace duplicate key error. And think when one updates they must be using the primary key as a matching value to update value.
Use
$this->Baker->updateAll(
array('Baker.approved' => 'Baker.approved + ' . $some_var),
array('Baker.id' => $someId)
);
For more information see: http://book.cakephp.org/2.0/en/models/saving-your-data.html