One model to several tables Laravel 5 - laravel-5

I have MySQL database tables, of which names are in "yyyymmdd" format. I need to select several tables, for example, from "20150901" to "20150930". I think there might be a way to implement only one model for those tables.
If somebody knows how to do so, please help.
Thanks.

immagine that this is your model.
class XYZ extends Eloquent {
public function __construct($table, array $attributes = array()){
parent::__construct($attributes);
$this->table = $table;
}
}
and you have 7 tables suppose for 1 week.
then inside controller loop you can have like
$reportData = array();
foreach($tables as $table) {
$xyzObj = new XYZ($table);
$reportData[] = $xyzObj->get();
//add your query stuff here like where and fetching records
}

Related

Laravel - can I make models dynamically and have relationships on each generated model?

I need to create Models based on the alphabet as their tables names are like 'products_a', 'products_b'....'products_z'. But I don't want to create all these models as separated files,
but want to find a way to use all these tables dynamically.
And all tables are separated based on some 'shopping-mall id' values.
I've found a solution to set tables dynamically like this solution.
So what I tried before was like below.
class Products extends Model
{
use BindsDynamically;
public $timestamps = false;
public $fillable = [ 'product_name', 'reg_time'];
public static function newProduct($mall_id)
{
$rangeArr = range('a', 'z');
$product = new Products;
foreach ($rangeArr as $ar) {
if (strtolower(substr($mall_id, 0, 1)) == $ar) {
$product->setTable('product_'.$ar);
}
}
return $product;
}
}
However, now I created a Cart model and tried to use the relationship methods with all the separated tables which I cannot.
So I realized I need the separated models with relationships not just tables.
Theoretically, my database has those tables.
products_a
products_b
....
products_z
products_cart
So, the products_cart table needs to have all the products tables idx data.
I want to use relationships like 'hasMany' or 'belongsTo', therefore I need all the separated models.
Can I make all the alphabetical models dynamically and use relationship methods?
If so, how can I do this?
OK, I understand we have a nasty DB design here. But then, we don't have a DB expert and I cannot figure what can I do about this DB design.
So, please don't judge about the DB design, rather guide the better way to replace it.
Maybe you UNION all product tables and overwrite the models newModelQuery() method to achieve that
class Products extends Model
{
use BindsDynamically;
public $timestamps = false;
public $fillable = [ 'product_name', 'reg_time'];
/**
* Get a new query builder that doesn't have any global scopes or eager loading.
*
* #return \Illuminate\Database\Eloquent\Builder|static
*/
public function newModelQuery()
{
$query = parent::newModelQuery();
$rangeArr = range('a', 'z');
foreach ($rangeArr as $ar) {
//if (strtolower(substr($mall_id, 0, 1)) == $ar) {
$query->union('product_'.$ar);
//}
}
return $query;
}
}
But that's probably just one of a couple methods you'd have to overwrite this way. And this solution currently doesn't support your $mall_id. But after all, it's due to bad database design.

Is there any possible way to generate database from models in Laravel?

Is there any possible way to generate database from models in Laravel ?
I am working on an existing laravel project,it contains models without their migrations.
I tried the reliese/laravel also the doctrine but nothing won't work ..any help ?
Suppose you have model Userwithout migration then you can get table name from it like
User::getTableName(); there is same function to get column names and you can get column types from protected $cast = []
Here is Sample code
$location = new LocationTable(); // load your model
$tableName = $location->getTable(); // this will give a table name from your model
$columnsWithType = $location->getCasts(); // set all your table fields as cast
Schema::create(tableName , function (Blueprint $table) use ($columnsWithType) {
foreach ($columnsWithType as $columnName => $type) {
$table->$type($columnName);
}
});

Laravel Eloquent - How to query all car models of given year where make is given?

I have these tables: Models, Year and Model_Year. The Model table has a make_id column referencing an id in Make table.
In my model I have defined a belongsToMany relationship between Model and Year.
This is what am doing so far in controller:
public function getModels() {
$year = Year::findOrFail(1);
$make = Vmake::findOrFail(1);
$models = $year->model->pluck('name','id');
return response()->json($models);
}
This returns all models of year with id 1.
How do I add a query to get only models where make_id = 1?
there is a simple solution for this. You just need to change function as I given below
public function getModels() {
$year = Year::findOrFail(1);
$make = Vmake::findOrFail(1);
$models = $year->model()
->where('make_id', 1)
->pluck('name','id');
return response()->json($models);
}
above is the changed code. Try and let me know if that not works for you.

latest() helper function in laravel

I'm building a small application where I'm having many to many relationship between two models something like this:
class Contact extends Model
{
public function company()
{
return $this
->belongsToMany('App\Company', 'company_contact', 'company_id', 'contact_id')->withTimestamps();
}
}
Now while retrieving this I want only the latest model through the pivot table or you may say relational table, for this I'm trying to implement:
public function getData()
{
$allData = Contact::all();
foreach($allData as $data)
{
$getCompany = $data->company()->latest()->first();
$data->company = $getCompany;
}
return response()->json(['model' => $allData], 200);
}
But I'm unable to retrieve the latest table it is showing the same old value or the first value.
Guide me how can I achieve this.
You can try this :
latest() is a function defined in Illuminate\Database\Query\Builder Class.
public function latest($column = 'created_at')
{
return $this->orderBy($column, 'desc');
}
So, It will just orderBy with the column you provide in descending order with the default column will be created_at
OR
public function getData()
{
$allData = Contact::all();
foreach($allData as $data)
{
$getCompany = $data->company()->orderBy('created_at', 'desc')->first();
$data->company = $getCompany;
}
return response()->json(['model' => $allData], 200);
}
So basically idea is if you are finding the relational data from many to many relation like $data->company() in this question and try to sort this with latest it will sort the company table with created_at sorting desc in order to get relational latest data you need to sort through pivot tables i.e.
$getCompany = $data->company()->withPivot('created_at')->orderBy('pivot_cr‌​eated_at', 'desc')->first();
This is how I achieved the latest relational table.
Note: You must have pivot table in your relation, in this answer created_at is the pivot field I'm using.

Many-to-Many and Eager loading query

I am new with Laravel, I was able to query Many-to-Many relationships. Where 'template_dynamic' is the pivot of two tables 'template' and 'dynamic'.
// Template Model
class Template extends Eloquent
{
protected $table = 'template';
protected $guarded = array('template_id');
protected $primaryKey = 'template_id';
public function dynamic()
{
return $this->belongsToMany('dynamic', 'template_dynamic')
->select('*')
->withPivot('template_dynamic_id')
->orderBy('template_dynamic_html_sort', 'ASC');
}
here I was able to retrieve the records
// Template Controller
$dynamic_fields = Template::find($rec->template_id)->dynamic;
what I want to do now is that pivot table has-many properties 'template_dynamic_option'. How will I query the records and combine it with $dynamic_fields variable?
// What I want to do is something like this. But sadly this is an invalid syntax
$dynamic_fields = $dynamic_fields->with('template_dynamic_option');
Any recommendation or enhancements are welcome.
Thank you in advance.
First, I am pretty sure you don't need the select('*') in your relationship query there.
But let's get to your actual problem ;)
To access the pivot table in Eloquent is pretty simple.
$dynamic_fields = Template::find($rec->template_id)->dynamic;
foreach($dynamic_fields as $dynamic){
var_dump($dynamic->pivot)
}
The thing is though, by default only the keys of the pivot table are present in the object.
To change that you have to define them with withPivot(). Actually like you already did but not with the id.
public function dynamic()
{
return $this->belongsToMany('dynamic', 'template_dynamic')
->withPivot('template_dynamic_option')
->orderBy('template_dynamic_html_sort', 'ASC');
}
And if you have multiple additional columns use this syntax:
->withPivot('template_dynamic_option', 'foo', 'bar');

Resources