I'm trying to create view in MySQL in Laravel by migration script. How can we create MySQL view by migration script in Laravel 4?
How about this? Haven't tested it, but I think it should work.
class CreateMyView extends Migration {
public function up()
{
DB::statement( 'CREATE VIEW myview AS SELECT [your select statement here]' );
}
public function down()
{
DB::statement( 'DROP VIEW myview' );
}
}
And then you can create a model to access it:
class MyView extends Eloquent {
protected $table = 'myview';
}
And then to access the view from elsewhere in your app you can query it like you would any other model, e.g.
MyView::all(); // returns all rows from your view
MyView::where( 'price', '>', '100.00' )->get(); // gets rows from your view matching criteria
Props go to the following which provided info on how to do this:
http://laravel.io/forum/05-29-2014-model-with-calculated-sql-field-doesnt-paginate
http://forumsarchive.laravel.io/viewtopic.php?pid=51692#p51692
CAVEAT
Be careful if later migrations modify the tables underlying your view. The reason is that per the documentation:
The view definition is “frozen” at creation time, so changes to the underlying tables afterward do not affect the view definition. For example, if a view is defined as SELECT * on a table, new columns added to the table later do not become part of the view.
Really, I guess you'd have to be careful of stuff like that for any migration, so maybe this is not such a big deal.
Related
I'm currently struggling with retrieving data towards a parent model. I'll drop my database, classes, and things I've tried before.
I have 4 tables: sales_orders, products, work_orders, and product_sales_order (pivot table between sales_orders and products).
SalesOrder.php
class SalesOrder extends Model
{
public function products()
{
return $this->belongsToMany(Product::class)
->using(ProductSalesOrder::class)
->withPivot(['qty', 'price']);
}
}
ProductSalesOrder.php
class ProductSalesOrder extends Pivot
{
public function work_orders()
{
return $this->hasMany(WorkOrder::class);
}
public function getSubTotalAttribute()
{
return $this->qty* $this->price;
}
}
WorkOrder.php
class WorkOrder extends Model
{
public function product_sales_order()
{
return $this->belongsTo(ProductSalesOrder::class);
}
public function sales_order()
{
return $this->hasManyThrough(
ProductSalesOrder::class,
SalesOrder::class
);
}
}
So, what I want to retrieve sales order data from work order since both tables don't have direct relationship and have to go through pivot table and that is product sales order. I've tried hasOneThrough and hasManyThrough but it cast an error unknown column. I understand that error and not possible to use that eloquent function.
Is it possible to retrieve that sales order data using eloquent function from WorkOrder.php ?
You cannot achieve what you want using hasOneThrough as it goes from a table that has no ID related to the intermediate model.
In your example you are doing "the inverse" of hasOneThrough, as you are going from a model that has the ID of the intermediate model in itself, and the intermediate model has the ID of your final model. The documentation shows clearly that hasOneThrough is used exactly for the inverse.
So you still should be able to fix this, and use a normal relation as you have the sales_orders_id in your model SuratPerintahKerja, so you can use a normal relation like belongsTo to get just one SalesOrder and define it like this:
public function salesOrder()
{
return $this->belongsTo(SalesOrder::class, 'sale_orders_id');
}
If you want to get many SalesOrders (if that makes sense for your logic), then you should just run a simple query like:
public function salesOrders()
{
return $this->query()
->where('sale_orders_id', $this->sale_orders_id)
->get();
}
Have in mind that:
I have renamed your method from sales_order to salesOrder (follow camel case as that is the Laravel standard...).
I have renamed your method from sales_order to salesOrders for the second code as it will return more than 1, hence a collection, but the first one just works with one model at a time.
I see you use sale_orders_id, but it should be sales_order_id, have that in mind, because any relation will try to use sales_order_id instead of sale_orders_id, again, stick to the standards... (this is why the first code needs more parameters instead of just the model).
All pivot tables would still need to have id as primary and auto incremental, instead of having the id of each related model as primary... Because in SuratPerintahKerja you want to reference the pivot table ProdukSalesOrder but it has to use both produks_id (should have been produk_id singular) and sale_orders_id (should have been sales_order_id). So if you were able to use something like produk_sales_order_id, you could be able to have better references for relations.
You can see that I am using $this->query(), I am just doing this to only return a new query and not use anything it has as filters on itself. I you still want to use current filters (like where and stuff), remove ->query() and directly use the first where. If you also want to add ->where('produks_id', $this->produks_id) that is valid and doesn't matter the order. But if you do so, I am not sure if you would get just one result, so ->get() makes no sense, it should be ->first() and also the method's name should be salesOrder.
Sorry for this 6 tip/step, but super personal recommendation, always write code in English and do not write both languages at the same time like produks and sales orders, stick to one language, preferrably English as everyone will understand it out of the box. I had to translate some things so I can understand what is the purpose of each table.
If you have any questions or some of my code does not work, please tell me in the comments of this answer so I can help you work it out.
Edit:
After you have followed my steps and changed everything to English and modified the database, this is my new code:
First, edit ProductSalesOrder and add this method:
public function sales_order()
{
return $this->belongsTo(SalesOrder::class);
}
This will allow us to use relations of relations.
Then, have WorkOrder as my code:
public function sales_order()
{
return $this->query()->with('product_sales_order.sales_order')->first();
}
first should get you a ProductSalesOrder, but then you can access ->sales_order and that will be a model.
Remember that if any of this does not work, change all the names to camelCase instead of kebab_case.
I'm confused on how to get my model setup in laravel with a table that is connected to a pivot table.
Here's the problem
Say I have
Locations
id
name
area_types
id
name
area_type_location (Pivot table)
id
location_id
area_type_id
area_test
id
area_type_location_id
clean
headCount
Relationship between the tables are different areas type belongs to different locations.
i.e: beach, 25m pools, kids pools, bbq, etc
area_test is connected to the pivot table because the test has to be generated from area that exists, in this case it is area that is registered under different locations. Thus it has to be tested daily, measured, etc.
I understand the structure between area_types and locations for many to many relationship, however I can't get over my head of how do i structure my area_test model? How do I get the data from locations table -> where are my test?
Should I create a model for my pivot table? Is that a good practice in laravel?
Does anyone has the same use case?
I read about eloquent has many through
relationship but I understand that it does not mention about getting through pivot table. I don't quite get if my use case is the same.
Thanks
Finally, apparently there are a couple of way to get data from locations table to area_tests
Tried at tinker and it works,
First Option
I need to create a Pivot model for my Pivot table:
class LocationAreaType extends Pivot{
public function location(){
return $this->belongsTo(Location::class);
}
public function areaType(){
return $this->belongsTo(AreaType::class);
}
public function AreaTests(){
return $this->hasMany(AreaTest::class, 'area_type_location_id');
}
}
I can use hasManyThrough relation that I need to create in my Location table
public function areaTests()
{
return $this->hasManyThrough(
AreaTest::class,
LocationAreaType::class,
'location_id',
'area_type_location_id');
}
this way I can get the areaTests easily by $location->areaTests, My problem was not determining the area_type_location_id as foreign. You need to determine this, apparently when I extends pivot and use hasMany laravel does not auto recognise the Foreign key by itself.
Second option
Another way to access it is from the relation table, I can define withPivot in the areaTypes() relation then access it like this:
$location->areaType[0]->pivot->areaTests
Since laravel only recognise foreign key from both tables location_id and area_type_id, I have to include the id of the pivot table to get the AreaTest table data
So in the Location model I have to get the column
public function areaTypes()
{
// Get the ID of the pivot table to get the poolTests table (connected with ID column)
return $this->belongsToMany(AreaType::class)
->using(AreaTypeLocation::class)
->withPivot('id');
}
There is no need to create a new model for pivot table.
Just declare in Location model below code:
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function area_types()
{
return $this->belongsToMany('App\AreaType', 'area_type_location', 'location_id', 'area_type_id');
}
and declare below code in AreaType model:
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function locations()
{
return $this->belongsToMany('App\Location', 'area_type_location', 'area_type_id', 'location_id');
}
every time you need to get for example the locations of an area_type in every controller, you can call the function like this: $areatype->locations()->get();
Don't forget to create area_type_location table migration.
I have 3 tables in a database
Transaction {'id','bill_id','remark'}
Bills {'id','third_party','amount'}
ThirdParty {'id','company_name',remark}
The 'transaction' table has column bill_id coming from 'Bills' and Bills table has 'third_party' column which connected to ThirdParty table column -> 'id'
So here I am trying to fetch company_name using laravel eloquent relation
My Transaction model:
public function Bills()
{
return $this->hasOne('App\Bills','id','bill_id');
}
Bills:
public function third_party()
{
return $this->belongsTo('App\ThirdParty','third_party','id');
}
I am getting null value for company_name
Here is the query i am using
Transaction::with('Bills.third_party')->get();
And i have corrected in question (third_party_name) to company_name column name i wrote here was my old join query name which is visible in screenshot, basically i am trying to fetch company name.
Are you able to show all of your code? How does company_name get set to third_party_name?
You could probably also gain a lot by sticking to the laravel "conventions" or "suggested naming", this will give you a lot of functionality for free, and make your code easier to read, write and debug.
eg. Your relationship method names (Bills(), third_party()), but more importantly if you name your table fields in the "laravel way", you will get easier eloquent relationships as there will be no need to define the foreign keys etc.
I would be setting this up similar to:
Transaction {'id','bill_id','remark'}
Bills {'id','third_party_id','amount'} <- note the third_party_id
ThirdParty {'id','company_name',remark}
class Transaction extends Model
{
public function Bills()
{
return $this->hasOne('App\Bills');
}
}
class Bills extends Model
{
public function ThirdParty()
{
return $this->belongsTo('App\ThirdParty);
}
}
You should also define the inverse relationships.
It would be very beneficial to see the full code to see where the issue is.
I'm starting to learn Laravel. I've run through the example instructions from the site successfully and now I'm trying a second run through and I'm running into an issue.
I'm trying to connect to a database called zipCodes and has one table called zipCodeDetails.
In my Laravel project I have a model containing the following code:
<?php
class ZipCodeDetails extends Eloquent {}
And in my routes.php file I have the following code:
Route::get('zipCodes', function (){
$zipCodes = ZipCodeDetails::all();
return View::make('zipCodes')->with('zipCodes', $zipCodes);
});
The error I'm running into is when I try to load the URL:
http://localhost:8888/zipCodes
In my browser I'm getting the error code:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'zipcodes.zip_code_details' doesn't exist (SQL: select * from `zip_code_details`)
There's nothing written in my code where I define the database zipCodes as zipcodes or the table zipCodesDetails as zip_code_details. Something in laravel is changing the database and table names.
Does anyone know why this is happening and how I can prevent it? I don't want to just rename the database or table names because while that may get me by in testing it's not a viable solution in practice.
Thanks!
This is the behaviour that uses if no table is being explicitly defined. In your ZipCodeDetails class, you can set the table name that this model will be using.
class ZipCodeDetails extends Eloquent
{
protected $table = 'zipCodesDetails';
}
How can one achieve multi table update/delete in atk4?
You can add related entities on the model level:
https://stackoverflow.com/a/7466839/204819
If this is not an option, you can always create custom handlers for your "edit" and "delete" button and perform actions using internal ORM or even on Model level.
You can use functions beforeInsert, afterInsert, beforeDelete, afterDelete and beforeUpdate, afterUpdate to carry out additional processing in the database. For example
using a unzipped install of ATK 4.1.3 in your webroot creates a folder called agiletoolkit which is referred to below as ATKHOME.
Create a simple table TASKTYPE in mysql with three fields (id, tasktype_desc and budget_code) and another table TASKTYPE_BUDGET with just id and budget_code.
Create two models for the tables in ATKHOME/lib/Model as follows (you may need to create the Model directory if it doesnt exist)
class Model_TaskType extends Model_Table {
public $entity_code='tasktype';
public $table_alias='ty';
function defineFields(){
parent::defineFields();
$this->newField('id')
->mandatory(true);;
$this->newField('tasktype_desc')
->mandatory(true);
$this->newField('budget_code')
->mandatory(true);
}
public function afterInsert($new_id){
$ttb=$this->add('Model_TaskTypeBudget');
$ttb->set('id',$new_id)
->set('budget_code',$this->get('budget_code'));
$ttb->insert();
return $this;
}
public function beforeUpdate(&$data){
$ttb=$this->add('Model_TaskTypeBudget')->loadData($data['id']);
$ttb->set('budget_code', $data['budget_code']);
$ttb->update();
return $this;
}
public function beforeDelete(&$data){
$ttb=$this->add('Model_TaskTypeBudget')->loadData($data['id']);
$ttb->delete();
return $this;
}
}
Note if you are using innoDB and have foreign keys, you have to do the insert and delete in the right order e.g. if there was a foreign key from TaskTypeBudget to TaskType on ID, then it should use beforeDelete and afterInsert to prevent constraint violations.
class Model_TaskTypeBudget extends Model_Table {
public $entity_code='tasktype_budget';
public $table_alias='tyb';
function defineFields(){
parent::defineFields();
$this->newField('id')
->mandatory(true);
$this->newField('budget_code')
->mandatory(true);
}
}
And a page in ATKHOME/page like this
class page_tasktype extends Page {
function init(){
parent::init();
$p=$this;
$tt=$this->add('Model_TaskType');
$crud=$p->add('CRUD');
$crud->setModel($tt, array('id','tasktype_desc', 'budget_code'));
if($crud->grid)
$crud->grid->addPaginator(10);
}
}
Note also be careful to include an opening < ? php tag before each class line but DO NOT include a closing ? > as this may cause errors in the Ajax.
In ATKHOME/config-default.php, modify the mysql connection username and password from root/root to the user and password of your mysql database.
$config['dsn']='mysql://atktest:atktest#localhost/atktest';
and modify ATKHOME/lib/Frontend.php to uncomment line 8 which allows all pages to connect to the database (you can also just add the $this->dbConnect(); line to the page.
class Frontend extends ApiFrontend {
function init(){
parent::init();
$this->dbConnect(); //uncommented
In the same Frontend.php, insert the following around line 50 to add a button to the default menu to add our new page.
->addMenuItem('CRUD Test', 'tasktype')
Now go to your webbrowser and enter http://localhost/agiletoolkit and on the first page, click CRUD Test. Adding rows will result in a row being added to TASKTYPE and a row with the same id and budget_code to TASKTYPE_BUDGET. Editing the budget_code will be reflected in both tables and deleting the row will delete it from both tables.
How neat and simple is that once you know the functions are provided by ATk4 ?