How to get the model name from the table name in CakePHP - mysql

In one of my projects, I have a function :
public function select($table){
$model=Inflector::singularize($table);
$result=$this->$model->find('all'));
...........
...........
}
Here, I tried to get the Model name from the given "table name"($table), and used find function of that model to select all data from that table. But that didn't work.
So, what should I do here ? Can anybody please help me ?
Thanks

You can use my trick. create table name as per model name, or using substr() or strstr() you can extract table prefix, then you can use your model ,
$tableName="myprefix_posts";
$dynamicModelName=strstr($tableName,"myprefix_");
$this->loadmodel($dynamicModelName);
if( $this->$dynamicModelName->save($this->data)){
// your code
}

You can use the Inflector class for the table name to be singularized. Example:
$dynamicModel = Inflector::singularize($table);
When you want to use the model via $this->Model you have to load it first.
$this->loadmodel($dynamicModel);

Just a friendly warning: Try not to use words that might be keywords in PHP or MySQL as variable or function names like you do in the function above (select). You or any other developers might get confused at later stages of development. There is probably no harm, I just don't recommend it.
Enjoy

Related

How to select database with dot in its name with laravel?

i have a project to show database value...
but, the database name has dot in it.
my database name is "t.produk".
How can i select the database in laravel?
i run it and got an error says it invalid like below
EDIT:
and i also did it with just string, came out error too :
Here the picture
First of all - avoid naming database tables like that. You should not use any dots there. It could be t_produk as example.
But table name should be descriptive so go for something like products. Than name your entity as Product.
You get this error here because you can't set variable as (t.produk). You should pass a string as I see here. So do it like this:
protected $table = 't.produk';
EDIT:
I saw the error with a string variable. So now you see why the current table naming you choose is quite not good. DB reads it as follows:
select from database t table produk
If you will name your table like t_produk problem should be no longer here.
My bad, so the tables name can't have dot in it. noted.
Btw y'all thanks for the answers :)

Can i use question mark in MySQL this way

i'm using node.js to build a web. I connect to my database (Mysql) and
get the data then return to the client side.
I know that i can use the literal template to write my sql expression like below
promise(`SELECT table.name FROM table WHERE name = ?`,[parameter])
and i'm would like to know can i write my sql expression like this?
promise(`SELECT table.? FROM table`,[parameter])
I know the result is different, i just want to know it is right or not.
thank you and have a nice day.
No, but you could use string interpolation like:
promise(`SELECT table.name FROM table WHERE name = ${parameter}`)

Getting another table's string via it's id

I have two tables, but since I can't format them here, you can check the table on this imgur img
The wildcard roles includes strings like department.* or blogger.department.*
I'm trying to create a role/permission inheritance system but i'm stuck on creating a many-to-many relationship
I've tried to use eloquent but since "wildcards" can't be/aren't a model , I can't use eloquent. So I tried to use the DB Facade but I'm not very good with SQL/DB so I've honestly got no clue on how to do this.
Here's what I need
Get the role ID (eg: admin = 1)
Get all wildcard_roles from the table role_wildcards by the Role ID
Return a collection of all the wildcard strings
Notes
It doesn't have to use eloquent, it can use the DB facade
It was actually quite simple after playing around
DB::table('role_wildcards')->where('parent_role_id', $this->id)->get();
Thought it'd be much more complicated
First of you create a relationship from role_wildcards to roles
public function role()
{
return $this->belongsTo('App\roles','parent_role_id','id');
}
then you use relationship like below
DB::table('role_wildcards')->with('role')->whereParentRoleId($this->id)->get();

Laravel Eloquent Advanced HAVING

I have a rather strange need from Eloquent. I need to represent the following query using the Eloquent way of doing things. The values come directly from user input so I don't know how best to proceed.
SELECT
GROUP_CONCAT(Table1.table2ID) AS table2ID,
GROUP_CONCAT(Table1.table3ID) AS table3ID
FROM
Table1
HAVING table2ID LIKE '%1%' AND (table3ID LIKE '%123%' OR '%456%')
AND table2ID LIKE '%2%' AND (table3ID LIKE '%789%' OR '%012%')
NOTE: This is an extremely reduced version of query to reduce confusion, but this is the part I am having the issue with.
$query->having(...) doesn't support the closure method that $query->where does.
If your query is too complicated for eloquent, think that the point of eloquent is doing more readable and easy the code. There is no need to overcomplicate yourself, create a scope where you can add a raw query to your Model, like this:
use Illuminate\Database\Eloquent\Model;
class MiModel extends Model
{
public function scopeHasWhatIneed($query)
{
return $query->select(DB::raw("your complex query here"));
}
}
Now you can play with your model, with understable code:
$mi_model->hasWhatIneed()->where(.....)->orderby...
Ah, notice that with raw queries you need to protect yourself from sql injection.

Creating an OR statement using existing conditions hash

I am working on a problem where I need to add an OR clause to a set of existing conditions. The current conditions are built in a hash in a method and at the end, they are used in the where clause. Here is a simplified example:
...
conds.merge!({:users => {:archived => false}})
Model.where(conds)
I am trying to add an OR clause to the current set of conditions so it would be something like '(conditions) OR new_condition'. I'd like to add the OR statement without converting each addition to the conds hash into a string. That would be my last option. I was hoping someone has done something like this before (without using Arel). I seem to recall in Rails 2 there was a way to parse a conditions hash using a method from the model (something like Model.some_method(conds) would produce the where clause string. Maybe that would be a good option to just add the OR clause on to that string. Any ideas are appreciated. Thank you for your help!
I found a way to do what I needed. Instead of changing all of the conditions that I am building, I am parsing the conditions to SQL using sanitize_sql_for_conditions. This is a private method in ActiveRecord, so I had to put a method on the model to allow me to access it. Here is my model method:
def self.convert_conditions_hash_to_sql(conditions)
self.sanitize_sql_for_conditions(conditions)
end
So, once I convert my conditions to text, I can add my OR clause (along with the appropriate parentheses) to the end of the original conditions. So, it would go something like this:
Model.where('(?) OR (model.type = ? AND model.id IN(?))', Model.convert_conditions_hash_to_sql(conds), model_type, model_id_array)