Can I actually make database queries without creating a new instance of the model?
For example, in my controller I have (CONTROLLER)
Name_Model::get_all_from_another_table();
and in my name_model.php (MODEL)
public static function get_all_from_another_table() {
$this->db->query('select * from another_table');
return $x;
}
This case happens for tables with predefined values to be loaded before creating new instances of model.
The above code returns:
Fatal error: Using $this when not in object context
Try it fisrt.
Controller:
$this->load->model( 'name_model' );
$data = $this->name_model->get_all_from_another_table()->result();
print_r( $data ); //just for testing...
Model:
//Model name: name_model.php
public static function get_all_from_another_table() {
$this->db->query('select * from another_table');
return $x;
}
Controller:
// Model File and Class Name first Character Must be Uppercase
$this->load->model( 'Name_model' );
$data = $this->Name_model->get_all_from_another_table();
print_r($data); //You result is print here
Model:
//Model name: Name_model.php
public static function get_all_from_another_table() {
$query = $this->db->query('select * from another_table');
return $query->result();
}
Related
I want to pass data from Controller to model.But I am unable to fetch it at the model side in CI.Kindly help me out.
Here is my controller function:
function show_chronicles($chronicle_num) {
$this->load->database();
//load the model
$this->load->model('Chronicles_model');
//load the method of model
$data['h'] = $this->Chronicles_model->show_seminar();
//return the data in view
$this->load->view('chronicles', $chronicle_num);
}
And here is my model:
public function show_seminar($chronicle_num) {
echo $chronicle_num;
//$this->db->select('*');
//$this->db->where('chronicles_no',$chronicle_num);
//$query1 = $this->db->get('chronicles');
//return $query1;
}
Its because your not passing any value to your model.
CONTROLLER
function show_chronicles($chronicle_num)
{
$this->load->database();
$this->load->model('Chronicles_model');
$data['h']=$this->Chronicles_model->show_seminar($chronicle_num);
$this->load->view('chronicles', $chronicle_num);
}
and you need to return the result() of your query
MODEL
public function show_seminar($chronicle_num = NULL)
{
return $this->db
->get_where('chronicles', array('chronicles_no' => $chronicle_num))
->result();
}
Controller:
function show_chronicles($chronicle_num) {
$this->load->database();
//load the model
$this->load->model('Chronicles_model');
//load the method of model
// pass it to model
$data['chronicle_num'] = $this->Chronicles_model->show_seminar($chronicle_num);
//return the data in view
$this->load->view('chronicles', $data);
}
And here is my model:
public function show_seminar($chronicle_num) {
return $chronicle_num;
//$this->db->select('*');
//$this->db->where('chronicles_no',$chronicle_num);
//$query1 = $this->db->get('chronicles');
//return $query1;
}
You just forgot to pass $chronicle_num as a parameter when you called $this->Chronicles_model->show_seminar();.
So the right way is $this->Chronicles_model->show_seminar($chronicle_num);
You can add as many parameters as you wish to the functions. Example:
public function show_seminar($chronicle_num, $param2, $param3) {
//Login here
}
Just remember to pass the parameters every time you call the function.
I am new to Laravel. I am trying to use Eloquent Model to access data in DB.
I have tables that shares similarities such as table name.
So I want to use one Model to access several tables in DB like below but without luck.
Is there any way to set table name dynamically?
Any suggestion or advice would be appreciated. Thank you in advance.
Model:
class ProductLog extends Model
{
public $timestamps = false;
public function __construct($type = null) {
parent::__construct();
$this->setTable($type);
}
}
Controller:
public function index($type, $id) {
$productLog = new ProductLog($type);
$contents = $productLog::all();
return response($contents, 200);
}
Solution For those who suffer from same problem:
I was able to change table name by the way #Mahdi Younesi suggested.
And I was able to add where conditions by like below
$productLog = new ProductLog;
$productLog->setTable('LogEmail');
$logInstance = $productLog->where('origin_id', $carrier_id)
->where('origin_type', 2);
The following trait allows for passing on the table name during hydration.
trait BindsDynamically
{
protected $connection = null;
protected $table = null;
public function bind(string $connection, string $table)
{
$this->setConnection($connection);
$this->setTable($table);
}
public function newInstance($attributes = [], $exists = false)
{
// Overridden in order to allow for late table binding.
$model = parent::newInstance($attributes, $exists);
$model->setTable($this->table);
return $model;
}
}
Here is how to use it:
class ProductLog extends Model
{
use BindsDynamically;
}
Call the method on instance like this:
public function index()
{
$productLog = new ProductLog;
$productLog->setTable('anotherTableName');
$productLog->get(); // select * from anotherTableName
$productLog->myTestProp = 'test';
$productLog->save(); // now saves into anotherTableName
}
I created a package for this: Laravel Dynamic Model
Feel free to use it:
https://github.com/laracraft-tech/laravel-dynamic-model
This basically allows you to do something like this:
$foo = App::make(DynamicModel::class, ['table_name' => 'foo']);
$foo->create([
'col1' => 'asdf',
'col2' => 123
]);
$faz = App::make(DynamicModel::class, ['table_name' => 'faz']);
$faz->create([...]);
I have to call a user model and get object only and then add the conditions.
How can I do this?
function manager(){
$email = 'xxxx#gmail.com';
$result = $this->user_model->getUserinformationData( );
$result1= $result->where('user.email',$email);
echo '<pre>';print_r($result1);exit;
}
function getUserinformationData(){
$querysucess = $this->db->select('*')->get('user');
return $querysucess;
}
Only get query object from model and add where or join condition another model or controller how can I do that one.
You have to pass variable from controller to model as function parameter:
//controller method
public function manager()
{
$email = 'xxxx#gmail.com';
$result = $this->user_model->getUserinformationData($email);//pass to the model
echo '<pre>', var_dump($result);
exit;
}
//model method
function getUserinformationData($email)//$email is passed from controller
{
$query = $this->db->get_where('user', ['email' => $email]);//second parameter of get_where() method as array of where conditions
return $query;
}
You have that in docs.
Sorry for posting such a noob question, but I've had hard times when working with returning a single
row from database and pass it to model. Here's my method from my model:
public function test($user_id)
{
$query = $this->db->query("SELECT COUNT(*) AS test FROM test WHERE user_id = '.$user_id.'");
return $query->first_row('array');
}
Here's an example of my controller with some other returned value from my model:
class MY_Controller extends CI_Controller
{
public $layout;
public $id;
public $data = array();
public function __construct()
{
parent::__construct();
$this->output->nocache();
$this->load->model('subject_model');
$this->load->model('user_model');
$this->load->model('survey_model');
$this->id = $this->session->userdata('user_id');
$this->data['check_if_already_posted_it_survey'] = $this->survey_model->checkIfAlreadyPostedSurvey('it_survey', $this->id);
$this->data['check_if_already_posted_lvis_survey'] = $this->survey_model->checkIfAlreadyPostedSurvey('lvis_survey', $this->id);
$this->data['test']= $this->survey_model->test($this->id);
$this->layout = 'layout/dashboard';
}
I can pass all the values from that data array to my view except "test". I've basically tried everything.
CheckIfAlreadyPostedSurvey method will return
number of rows with num_rows and I can easily print the value from them in my view by writing:
<?=$check_if_already_posted_it_survey?>
What should I do to print out that "test" in my view?
Thanks in advance and apologizes...
I probably got the question wrong, but have you tried
echo $this->survey_model->test($this->id);
Try this:
public function test($user_id)
{
$query = $this->db->query("SELECT COUNT(*) AS test FROM test WHERE user_id = '".$user_id."'");
return $query->row()->test;
}
This will return a single row as an object and then the referenced row name, which in this case is test.
The following will also work.
public function test($user_id)
{
$query = $this->db->query("SELECT * FROM test WHERE user_id = '".$user_id."'");
return count($query->result());
}
You also messed up the quoting in your SQL statement.
I have variables that are created and used on my model that I need to be able to use on my controller how is that accomplished?
Edit:
Controller: http://pastebin.com/jhAwAVa6
Model: http://pastebin.com/9xXRyYAa
It's unclear from your question, what exactly you want to do.
If it is about accessing model properties, the right way is using accessor methods:
class Model extends CI_Model{
private $name;
public function getName() {return $this->name; /*any other logic here*/}
public function setName($value) {$this->name= $value; /*any other logic here*/}
}
You can not pass the variable from a model to controller.
You can access public variables of a model through a controller.
echo $this->model_name->variable_name;
Model (my_model)
function useful_info()
{
$data = new stdClass();
$q = $this->db->get('users');
$data->users = $this->db->result();
$data->date = date('Y-m-d');
$data->info = array('whatever','more','anything');
return $data;
}
Controller
function index()
{
$info = $this->my_model->useful_info();
foreach($info->users as $user)
{
echo $user->id;
}
echo $info->date;
if($info->info[0] == 'whatever')
{
// do something
}
}
You don't have to create an object (it can be a string, T/F, array, etc), but you usually need to return something from your model and library functions. And you can access what you return by returning it to a variable $info = $this->my_model->useful_info();