Laravel seeding tables in second database - mysql

connection('mysql2') is my (working) second database connection.
When I migrate first, connection('mysql2') is working like expected, the table is created.
Schema::connection('mysql2')->create('brands', function(Blueprint $table)
{
//...
});
But when I try to seed tables in my second database:
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use App\Brands;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Model::unguard();
$this->call('BrandsTableSeeder');
$this->command->info("Brands table seeded.");
}
}
class BrandsTableSeeder extends Seeder
{
public function run()
{
DB::connection('mysql2')->table('brands')->delete();
Brands::connection('mysql2')->create(['brand' => 'test']);
}
}
I got:
[BadMethodCallException]
Call to undefined method Illuminate\Database\Query\Builder::connection()

Problem with your code is you have used Connection() method with Eloquent(not DB), Eloquent doesn't have connection() method.
You can use on() method with model(Eloquent) to specify connection
$user = User::on('mysql2')->create(['brand' => 'test']);
reference http://laravel.com/docs/4.2/eloquent#basic-usage
or
instead of writing on('mysql2') everywhere
you can write following code in model
protected $connection = 'mysql2';
and now seed is written as
class BrandsTableSeeder extends Seeder
{
public function run()
{
Brands::truncate();
Brands::create(['brand' => 'test']);
}
}

Related

Fetch data in codeigniter construct function

I try to fetch data from database in codeigniter construct function
but getting undefined method error
controller-
class Welcome extends CI_Controller
function __construct()
{
parent::__construct();
$this->load->model('Login');
$this->Login->getadminnav();
}
}
model-
class Login extends CI_Model
{
public function adminnav()
{
$query="SELECT * from adminnav where status='1'";
$query->row_array();
return true;
}
}
You got to load the model you are using first:
$this->load->model('login_model');
$this->Login->getadminnav();
And remember to rename the model to Login_model
Try these pieces of code.
Controller:
class Welcome extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('Login');
$this->Login->adminnav();
}
}
Model:
class Login extends CI_Model{
public function adminnav(){
$this->load->database();
$sql = "SELECT * from adminnav where status='1'";
$result = $this->db->query($sql);
return $result;
}
}
I am seeing in your code that-
In controller you didn't start the second bracket after controller name.
You defined the function name as "adminnav" in model but called it as "getadminnav" in Controller
You didn't load the database in model (If you already loaded it in autoload.php then here is not needed)
Anyway please let me know whether your problem is solved or not.
you are calling getadminnav() but in your model the method name is adminnav.and change model name Login to Login_model.
try this:
class Welcome extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('Login_model');
$this->Login->adminnav();
}
}
// model
class Login_model extends CI_Model{
public function adminnav()
{
$query="SELECT * from adminnav where status='1'";
$query->row_array();
return true;
}
}

Eloquent queries wrong table in many-to-many relationship

I'm having trouble with a many-to-many relationshop. When querying the relationship (tested in tinker) I'm getting an error message triggered by sql showing me a query on the wrong table.
My models:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Slideshow extends Model
{
public function pictures ()
{
return $this->hasMany(Picture::class);
}
}
namespace App;
use Illuminate\Database\Eloquent\Model;
class Picture extends Model
{
public function slideshows ()
{
return $this->belongsToMany(Slideshow::class,'slideshowpictures')->withPivot('order')->withTimestamps();
}
}
My migration for this relationship:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateSlideshowpicturesMigration extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up ()
{
$tablename = 'slideshowpictures';
Schema::create($tablename, function (Blueprint $table)
{
$table->integer('slideshow_id')->unsigned();
$table->integer('picture_id')->unsigned();
$table->integer('order')->unsigned();
$table->timestamps();
});
Schema::table($tablename, function ($table)
{
$table->foreign('slideshow_id')->references('id')->on('slideshows')->onDelete('cascade');
$table->foreign('picture_id')->references('id')->on('pictures')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down ()
{
Schema::dropIfExists('slideshowpictures');
}
}
Now in tinker I get the following error:
>>> $slide =Slideshow::all()->first();
=> App\Slideshow {#751
id: 1,
name: "1",
occasion_id: 1,
created_at: "2017-09-16 19:01:59",
updated_at: "2017-09-16 19:01:59",
}
>>> $slide->pictures()->exists();
Illuminate\Database\QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'pictures.slideshow_id' in 'where clause' (SQL: select exists(select * from `pictures` where `pictures`.`slideshow_id` = 1 and `pictures`.`slideshow_id` is not null) as `exists`)'
>>> $slide->pictures();
=> Illuminate\Database\Eloquent\Relations\HasMany {#830}
I could not yet find an answer and hope you can help me figure out why it is selecting from my pictures table and not the junction table which I created.

The table does not exist: {{%active_record}}

I am new to yii and learing generating the CRUD operation through gii first i create a country table and generate the model and controller and views using gii i am get following error
Invalid Configuration – yii\base\InvalidConfigException The table does not exist: {{%country_search}}
Add this to CountrySearch class:
/**
* #inheritdoc
*/
public static function tableName()
{
return 'country';
}
Just adding to temirbek answer:
file models/Country.php
<?php
namespace app\models;
use yii\db\ActiveRecord;
class Country extends ActiveRecord
{
public static function tableName()
{
return 'country';
}
}

Getting a Parse error: syntax error, unexpected '$faker' error when seeding

I am getting the following error when trying to seed in Laravel 5.4
[Symfony\Component\Debug\Exception\FatalThrowableError]
Parse error: syntax error, unexpected '$faker' (T_VARIABLE), expecting function (T_FUNCTION) or c
onst (T_CONST)
Here is the code for the seed file.
<?php
use Illuminate\Database\Seeder;
use App\Book;
use Faker\Factory as Faker;
class BookSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
$faker = Faker::create();
public function run()
{
foreach (range(1, 30) as $index) {
Book::create([
'title'=> $faker->sentence(5),
'author'=> $faker->sentence(7),
'description'=>$faker->paragraph(4)
]);
}
}
}
I have created the model and done the migration. I can't seem to find any good tutorials on how to do this with Laravel 5.4 . Any help would be appreciated.
Declare $faker variable in run method will solve the problem
`<?php
use Illuminate\Database\Seeder;
use App\Book; use Faker\Factory as Faker;
class BookSeeder extends Seeder
{
/**
* Run the database seeds. *
* #return void */
public function run() {
$faker = Faker::create();
foreach (range(1, 30) as $index) {
Book::create([
'title'=> $faker->sentence(5),
'author'=> $faker->sentence(7),
'description'=>$faker->paragraph(4)
]);
}
}
}`

Laravel 5 - Eloquent relationship returning an empty collection

I'm having trouble with a Laravel 5 relationship. I have 2 models Crew and Event with the corresponding tables crews and events. Crews have many events, and events have one crew. I set up my models and migration as follows:
Schema:
//Crews
Schema::connection('scheduling')->create('crews', function ($table) {
$table->increments('id');
$table->text('name');
$table->boolean('solo');
$table->boolean('active');
$table->text('phone');
});
//Events
Schema::connection('scheduling')->create('events', function ($table) {
$table->increments('id');
// ...
$table->integer('crew_id')->unsigned();
$table->foreign('crew_id')->references('id')->on('crews');
$table->text('notes');
// ...
$table->timestamps();
});
Models:
namespace App\Models\Scheduling;
use Illuminate\Database\Eloquent\Model;
class Crew extends Model {
public $connection = "scheduling";
public $table = "crews";
public function events() {
return $this->hasMany('App\Models\Scheduling\Event', 'id', 'crew_id');
}
public static function active() {
return Crew::where('active', 1)->get();
}
}
namespace App\Models\Scheduling;
use Illuminate\Database\Eloquent\Model;
class Event extends Model {
public $connection = "scheduling";
public $table = "events";
public function crew() {
return $this->belongsTo('App\Models\Scheduling\Crew', 'crew_id', 'id');
}
}
If I run Crew::find(102)->events; I end up with an empty collection.
If I run Events::where('crew_id', 102)->get(); I end up with the list of events I expected.
Any idea what I'm doing wrong here?
Your definition of events relation is invalid - you pass the arguments in wrong order.
Replace:
return $this->hasMany('App\Models\Scheduling\Event', 'id', 'crew_id');
with
return $this->hasMany('App\Models\Scheduling\Event', 'crew_id', 'id');
or simply
return $this->hasMany('App\Models\Scheduling\Event');
as you are using the default values for the column names, so no need to pass them to the relation definition.