Get model name dynamically in cakephp 2.x - model-view-controller

Is there any function to get the all table or model names in cakePhp.
I want to update my table's field and for that I need to select all table dynamically so that in future when I'll add new table I do not have to make changes in function.
The new table automatically update the fields.

I don't quite understand the question - from what i gather you want to write abstract actions to account for multiple models? If this is the case you can add abstract actions into the AppController and use $this->modelClass. This will return the model name from were you are calling the abstract action from. For example if you calling the abstract action from 'UsersController' which by default uses the Model 'User' then the modelClass will return 'User'.
class AppController extends Controller {
public function abstractAdd() {
// Get the model in use
$this->{$this->modelClass}->create();
// Use the save method in that model
if ($this->{$this->modelClass}->save($data)) {
// do something
}
}
}
class UsersController extends AppController {
public function add() {
$this->abstractAdd();
}
}
Hope this helps

Related

Laravel eager loading a BelongsTo relation doesn't work

This seems extremely simple and yet it doesn't work:
// Reservations
class Reservation extends Model
{
public function service()
{
return $this->belongsTo('App\Landing');
}
}
// Service
class Landing extends Model
{
public function reservation()
{
return $this->hasMany('App\Reservation');
}
}
And then in my controller I have:
$x = Reservation::with('service')->get();
$y = Reservation::all()->load('service');
None of these work. I've tried several ways of loading it and none of them work. It always returns an empty result for the service.
Any other result works fine with eager loading (even with nesting) except te BelongsTo - this one.
The eager loading works.
The problem is your relationship
When you define a BelongsTo relationship you need to specify a foreign key if the name of your property does not correspond to the entity being referenced
For example: if you call the relationship "landing", you will be fine, because under-the-hood, Laravel passes the foreign key landing_id based on the name of the property
class Reservation extends Model
{ //landing correspond to the lowercase (singular) name of the Landing class
//in that case Laravel knows how to set the relationship by assuming
//that you want to match landing_id to the id of the landings table
public function landing()
{
return $this->belongsTo(Landing::class);
}
}
If you chose to name the relationship differently, such as "service", then you need to specify the foreign key ex: landing_id since service and landing are two different words, and landing correspond to the lowercase version of the actual class Landing. Otherwise Laravel would think your foreign key is "service_id" instead of landing_id
class Reservation extends Model
{
//service is a custom name to refer to landing
//in that case Laravel needs you to specify the foreign key
public function service()
{
return $this->belongsTo(Landing::class, 'landing_id');
}
}
Read more here: https://laravel.com/docs/5.8/eloquent-relationships#updating-belongs-to-relationships

How to eager load a relation with a condition in Eloquent?

I have a relation that can be inherited from a parent if not set for the object itself.
For an example setup let's say we have events that have a venue.
class Event extends Model
{
public function venue()
{
return $this->belongsTo('App\Venue');
}
public function activities()
{
return $this->hasMany('App\Activity');
}
}
And there are activities in the events that mostly take place in the same venue, but sometimes could be elsewhere while still belonging to the same event.
class Activity extends Model
{
public function event()
{
return $this->belongsTo('App\Event');
}
public function venue()
{
if ($this->venue_id)
return $this->belongsTo('App\Venue');
return $this->event->venue();
}
}
If I simply request activities for an event and work with them it is fine. But if I try to eager load the venues for activities, I only get the ones that are set directly on the activity, never requesting one from parent.
$activities = $event->activities;
$activities->load('venue'); // Works correctly without this line
foreach ($activities as $activity)
if ($activity->venue) // Doesn't take venue from the parent (event)
echo $activity->venue->name; //Only shows if venue_id is set on activity
Is there any chance to fix the relations so I could load them in bulk?
By their very nature, eager loaded relationships do not have the relationship method run for each parent model. If they did, you would have the N+1 issue, which is exactly what eager loading is meant to solve.
The relationship method is run once on the model that is used to start the query. This gets the base query to run, and then all of the parent model ids are injected into that query.
In order to do what you want, you need to change things up a little bit. First, your Activity can be directly related to venues, so setup that relationship without any conditions. Next, create an accessor method that will return the proper venue for the Activity.
So, your code would look something like:
class Activity extends Model
{
public function event()
{
return $this->belongsTo('App\Event');
}
public function venue()
{
return $this->belongsTo('App\Venue');
}
public function getActivityVenueAttribute()
{
return $this->venue ?? $this->event->venue ?? null;
}
}
The other option would be to always assign the venue_id on the Activity, even if it is the same as the Event venue_id. Then you don't need to worry about the venue id missing on the activity.

Laravel - Extending Model

I've created a BaseModel class, which extends from Model. It seemed like everything was working fine, but now I've run into a problem when saving. I'm overriding the save() method in this BaseModel. I'd just like to add some attributes to the model before saving. So I do that, then call return parent::save($options);. The method signature is still the same: public function save(array $options = []).
It appears to be grabbing the name of the BaseModel class for the table name when performing the insert (it's using base_models as the table name), rather than the actual model that is being saved. Has anyone run into this before? What is the proper way of extending from the model class?
I originally created some traits to handle some extra functionality, but thought it would be a better idea to just create a base model and have my models extend from that instead.
In your model (the child one that extends the base model) add the table name explictly for example:
class SomeChildModel extends BaseModel {
// Manually set the table name
protected $table = 'table_name';
}
I realized that I previously had a static method that was creating an instance of itself using new self() and would set a few attributes, back when I was using the methods from a trait. It was fine before, but now since I moved the methods into the base model, that method was actually being called on the base model itself rather than the class that had the trait.
I was basically using the static method to instantiate the class, as I've read it's one way to avoid cluttering the constructor. But I just opted to do it in the constructor this time around since it made sense, so that was my solution.
Laravel will use snake case of the class name by default (the class where save method is called), if no $table instance variable is set. In your case it will use snake case of the BaseModel as a table name. You have two solutions:
Solution 1:
In classes which extends BaseModel add the $table instance variable as follow:
class User extends BaseModel {
protected $table = 'table_name'; // Your table name in the database;
}
Solution 2:
You can use Laravel Eloquent's Events, which allows you to hook into various points in the model's lifecycle.
You can hook into the save method as follow and make your changes. You can use these methods in your BaseClass, in traits, etc. For example in your BaseModel:
class BaseModel extends Model
{
/**
* Listen for save event
*/
protected static function boot()
{
parent::boot();
static::saving(function($model)
{
if ( ! $model->isValid()) {
return false;
}
});
}
}
The above will always call isValid before a model is saved into the storage. In this case it will return false and will not save the object.
For more info see the official docs here. Let me know if it isn't clear.

Ordering table data

I already read this piece from the laravel 5.1 documentation:
$users = DB::table('users')
->orderBy('name', 'desc')
->get();
I have no ideia where to write that.
And this is what I tried to write inside my Model:
class Professor extends Model
{
$professor = DB:table('professor')->orderBy('name','asc')->get();
}
Also tried:
class Professor extends Model
{
Professor::orderBy('name')->get();
//$professor = Professor::orderBy('name')->get();
}
Nothing works e.e
All of them give me erros like:
syntax error, unexpected '$professor' (T_VARIABLE), expecting function (T_FUNCTION)
The piece of code your trying to write should not be placed inside a Model. It should be in a controller or a repository if your using a Repository Pattern.
Assuming you got the following in your code.
A table called professors. A model Professor . A Controller called ProfessorsController.
And a route file with the following code get('professors','ProfessorsController#index');
Then on the controller you should have the following code.
class ProfessorsController extends Controller {
public function index()
{
$professors = \DB:table('professors')->orderBy('name','asc')->get();
return view('proffesors')->with('proffessors',$professors);
}
}
This will return an order list of professors to the view. That is if you are using a view to represent the data.
It does not need to be in model. Most of time something like that goes in controller.
In model you need to define relations or functions that would be used application wide on a object.
If you want to do something similar in model you won't use DB::table you need something like:
class Professor extends \Eloquent
{
public function professorsByName(){
$professionCollection = Professor::all()->orderBy('name','asc')->get();
return $professionCollection;
}
}
Please take it as example it's not something that should go in model at least this simple not.
Mental Note
Never use DB::table reason your observer if any won't execute.
I think you all are missing the primary issue with
class Professor extends Model
{
$professor = DB:table('professor')->orderBy('name','asc')->get();
}
This is not how PHP classes work.
OP, you need to brush up on the concepts of OOP.
What you need is something like this:
your controller:
public function myRoutedMethod()
{
$professors = Professor::getModel()->orderBy('name','asc')->get();
foreach($professors as $professor)
{
var_dump($professor->toArray();
}
}
Or probably even better, create a repository to interface with your model and just call $repository->professors()->toArray();
Google search: Laravel Repository

Different Models in Magento for same Module:

I create a Module in Magento, Now i am want to Use the Other model to take collection but thats give me error,
**Error:** There has been an error processing your request
Exception printing is disabled by default for security reasons.
Error log record number: 1685082734
And my Collection class is given below..
class Mage_Banners_Model_Mysql4_Category_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
{
public function _construct()
{
parent::_construct();
$this->_init('banners/category');
}
}
So how to run this and how this model resource know about has table..?
If you want to add another model to your custom module, you should enter your table name in config.xml file, which is located in yourmodule/etc folder:
<entities>
<banners>
<table>Your table Name here</table>
</banners>
After that you should add your collection class in corresponding model/mysql4/category/Collection.php. You should create model class in model/file name.
Suppose category.php is the model file, you should initiate that model class by using these methods. These files should be in the model folder:
public function _construct()
{
// Note that the category_id refers to the key field in your database table.
$this->_init('banner/category', 'category_id');
}

Resources