I'm learning laravel 5 and it's relationship with databases. I can find tons of info regarding how to work with sqlite and mysql but I'm having problems understanding what migrations are, how they are related with databases and my main issue...
If I have a pre-created postgres database with, let's say, 10 tables and their relationships already up and running, how can I make Laravel interact with them?
For example, I have my postgres schema table defined like this:
CREATE TABLE "users" (
"id" integer NOT NULL DEFAULT nextval('users_seq'),
"name" character varying(30) NOT NULL,
"email" character varying(50) NOT NULL UNIQUE,
"password" character varying(120) NOT NULL UNIQUE,
CONSTRAINT users_pk PRIMARY KEY ("id")
) WITH (
OIDS=FALSE
);
I already know Laravel comes with a generic migration for users table but how exactly should I work from within Laravel connecting to my db?
By the way, my database's name would be dummy.
May I use something like a migration class?
But as far as I understand, migrations are for creating/deleting/etc tables, right?
Or should I directly create a controller to interact with de db like these?
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
class PagesController extends Controller
{
public function index()
{
$users = DB::table('users')->get();
return view('DBHandler',compact('users'));
}
}
And I imagine this is the query builder way of doing things and eloquent's way is quite different.
Any help would be appreciated.
According to Documentation of Laravel:
Migrations are like version control for your database, allowing a team to easily modify and share the application's database schema. Migrations are typically paired with Laravel's schema builder to easily build your application's database schema.
If you have a team working with you, is highly recommendable to use them for changes that must be applied on the scheme to the application works, these migrations let you to apply changes to database like drop, create, update, etc. On the other hand if you're going to start developing with a Schema already created, there is no problem you can interact with your scheme with Eloquent.
The way as Laravel take information from your database is with Eloquent a ORM, Here is the introduction from Laravel Documentation:
The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table.
So you have to create a Model for each one of your tables, except tables many to many. If your table is Users you must name the model User and Eloquent take it automatically if not, you must overwrite the $table attribute at the model like this:
public $table = 'user';
The rest what you can do with Eloquent you can find it at the documentation here
I hope this helps you out.
From the blog laravelbooks.com, quoting:
[...] Migrations are the Laravel way of helping you to evolve the database schema of your application (also known as its DDL) without having to drop and re-create the database each time you make a change. And not having to drop and recreate the database each time a change happens means that you don’t lose your development data. The only changes made when you execute a migration are those necessary to move the schema from one version to another, whether that move is forward or backward in time.
Not only does Laravel migration provide you with a means to change your database schema in an iterative manner, but it lets you do so using PHP code, rather than SQL! The Laravel Schema Builder allows us to create database tables and insert columns or indices quickly. It uses clean and expressive syntax to make database operations happen. You may think of Laravel migration as version control for your databases! [...]
There I found a more explanatory way to laravel than the official documentation, though the later it's also good
Related
Is it possible to set foreign keys between tables of two different databases in laravel? it's possible
Cross database foreign keys hasn't much to do with Laravel actually.
MySQL (at least with InnoDB) does support foreign key constraints across multiple databases. You just have to specify the database with the dot notation:
Regarding the Laravel schema builder, this should work:
$table->foreign('user_id')->references('id')->on('main_db.users');
// ^^^^^^^
If you get an error, check if the column types are the same.
You can't reference varchar to int or vice-versa, keys have to be of
same type
Go through Foreign key cross database for more details
IF, and only if your underlying database supports it, then there should be a way to translate this business rule to a Laravel app.
Maybe not using their fancy built-in ORM. But surely it's possible to write a migration for it using DB::statement or even DB::unprepared. But as the code for such a setup is not database agnostic this is against best practices, but not impossible.
You then must configure two (or more) connections, one for each database and use the property $connection on you models to tell Laravel on which database each model is. You will be able to even use Eloquent relations this way between models in different databases.
So basically I needed to change the id type of the jobs and failed jobs migrations created by laravel to uuid, but it shows me this error.
SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column \"id\" violates not-null constraint.
I'm using the queue database driver.
I've tried to change the model in the framework files and works somewhat ok, but this is like my critical nuclear solution.
If there is a better and more optimal solution you can think of please go crazy.
Thanks in advance!
The problem is caused by laravel not generating UUID automatically. Normally, if you want a model to use uuid, you override its boot function and provide uuid creation logic. For instance, you can see it in action here:
https://medium.com/binary-cabin/automatically-generating-a-uuid-on-your-laravel-models-b8b9c3599e2b
However, jobs and failed-jobs tables are not models. If you inspect Illuminate/Queue/DatabaseQueue class, you will see that it just do basic DB updates, inserts. So if you really have to change these tables to use UUID, only option you have is to refactor this core laravel code which is not suggested.
Another approach you can take is, create 2 new intermediate models (e.g. MyJob and MyFailedJob) for jobs and failed jobs, and with sql triggers on original table populate these table. You can use uuid on these intermediate models.
Hope it helps
I'm doing a web app here using Laravel + AngularJS and I have a question.Do I need a model for each table that I have in my database? There are 87 tables in my database and I need to query all of them according to with the input that the User wants.
I just want to make sure with all tables must have a model file or if just one is enough.
There are 2 ways by which you can access your DB tables:
Eloquent ORM (dependent on Models)
DB Facade Query Builder(independent on Models)
Former, is more clean and best approach to perform DB query and related task, whereas latter is not clean, and it is going to be difficult for you to manage large application, as you told there are 80+ tables in your application.
Also, if you're using Eloquent way, then it's also a better to have a base model, which will have common code which you can inherit in child models. Like if you want to store "user id" who did some DB changes, then in the boot function, you can write Auth::id() and assign that value to changed_by field on your table.
In DB Facade way, you've to hard code table name every time you're performing DB operation, and which leads to inconsistency when you found that you've to change the name of the table, it's a rare scenario still it'll be difficult to manage if in a file there are multiple tables DB operation going on. There are options like, creating a global table name variable which can be accessed to perform DB operation.
Conclusion:
Yes, creating 80+ model for implementing Eloquent way is painful, but for a short term, as the application grows it will be easy for you to manage, it will be good for other developer if they start working on it, as it will give a overview of DB and it will improves code readability.
It depends on how you'd like to handle queries.
If you'd like to use Eloquent ORM, you need model classes to handle objects and relationships. That is a model for a table, except intermediate relationship tables, which may be accessed through pivot attribute.
Raw SQL queries are also supported. You don't really need model classes for them, as each result within the result array will be a PHP StdClass object. You need to write raw SQL though.
See Laravel documentation.
I have two tables in DB (topic, topic_content):
what kind of entities i should create for symfony2?
I think, i should have something like this in my symfony structure (Entities/Topic.php, Entities/Topic_content.php) help me please..
Yes, you would create Topic and Topic Content. And likely also a User Entity (because user_id looks like a foreign key).
However, the idea in Symfony2 is to approach the application from the Model site instead of the database site. Quoting https://doctrine-orm.readthedocs.org/en/latest/tutorials/getting-started-database.html:
Development Workflows
When you Code First, you start with developing Objects and then map them onto your database. When you Model First, you are modelling your application using tools (for example UML) and generate database schema and PHP code from this model. When you have a Database First, you already have a database schema and generate the corresponding PHP code from it.
For database first, there is a generator that will derive objects based on your schema:
https://github.com/beberlei/DoctrineCodeGenerator
The recommended approach though is to have Doctrine generate the db schema from your Entities.
Quoting Getting Started - Generating the DB Schema
Doctrine has a Command-Line Interface that allows you to access the SchemaTool, a component that generates the required tables to work with the metadata.
It requires some setup, which is explained in the guide. Once you have that, you simply tell Doctrine to generate or update your schema, whenever your object structure changes.
What is the method to save and update Many to Many relationship in Yii framework?
There is a better implementation as behavior.
http://www.yiiframework.com/forum/index.php?/topic/6905-please-test-my-ar-enhancement-automatically-sync-many-many-table-when-calling-save/
Unless you create a model for the table between the two main tables, your only option is to use DAO (Database Access Object) and specify SQLs with it.
Have a look at how blog demo accomplishes this task.
use MANY_MANY relationship type to setup many to many connection between Models (An associative table is needed to break a many-to-many relationship into one-to-many relationships)
And now you can use all relational functions of Active Records
Yii Framework - The Definitive Guide to Yii: Working with Databases-Relational Active Record
The following extension does what you want...
Yii Framework - Extension: cadvancedbehavior
An important thing to note: On each update, the extension clears all previous records and creates new ones. So I wouldn't use it when the intermediatry table contains extra data other than the foreign keys.
you could set that up in mysql level..by going to relational view under each table in phpmyadmin and provide necessary relational condition..and use MANY_MANY in the model class inside relations..
The question is too common.
Usually data components with MANY to MANY relationships appear sequentially and independently. So you just need to do one insert action after another.
If your relationship needs dependent update you should user SQL triggers on the DataBase level. That'll ensure integrity of data and give a quite good separation in business logic of the application.
CREATE TRIGGER some_trigger
AFTER UPDATE ON some_table
...
END IF;
A similar way is to incapsulate relational data in one logical model on PHP level (and e.g. manipulate with 2-3 AR models there) and emulate SQL triggers logic in it.