So i want to fetch data from two tables.
But i got this error :
Here is my Query from Model:
public function tampil_edit($id) {
$this->db->join('tb_m_user', 'tb_m_user.id=tb_m_notaris.id');
$this->db->select('tb_m_notaris.*,tb_m_user.email as email_notaris');
return $this->db->get_where('tb_m_notaris', $id);
}
Here is my Controller :
public function tampiledit($id) {
$id = ['id' => $id];
$title['title'] = 'Notaris | Edit';
$data['notaris'] = $this->m_notaris->tampil_edit($id)->result();
$this->load->view('template/headercss',$title);
$this->load->view('template/sidebar');
$this->load->view('template/navbar');
$this->load->view('master_data/notaris/edit', $data);
$this->load->view('template/footerjs');
}
Here Is what the $id contain:
Check your SQL
WHERE id = 45
^^
This id belongs to which table? I notice there are multiple table (tb_m_notaris,tb_m_user) with id column.
To call function
tampil_edit(45) {} # makesure $id is not an array
In model
public function tampil_edit($id) {
$this->db->select('tb_m_notaris.*,tb_m_user.email as email_notaris');
$this->db->from('tb_m_notaris');
$this->db->join('tb_m_user', 'tb_m_user.id = tb_m_notaris.id');
$this->db->where('tb_m_notaris.id', $id);
return $this->db->get()->result();
}
You should try this.
public function tampil_edit($id) {
$this->db->select('tb_m_notaris.*,tb_m_user.email as email_notaris');
$this->db->join('tb_m_user', 'tb_m_user.id=tb_m_notaris.id');
$this->db->get_where('tb_m_notaris', array('tb_m_notaris.id' => $id));
return $this->db->get()->row_array();
}
update this in your controller
$data['notaris'] = $this->m_notaris->tampil_edit($id);
you should pass like this in your controller
public function tampiledit($id) {
$id = ['tb_m_notaris.id' => $id];
$title['title'] = 'Notaris | Edit';
$data['notaris'] = $this->m_notaris->tampil_edit($id);
$this->load->view('template/headercss',$title);
$this->load->view('template/sidebar');
$this->load->view('template/navbar');
$this->load->view('master_data/notaris/edit', $data);
$this->load->view('template/footerjs');
}
public function tampil_edit($id) {
$this->db->select('tb_m_notaris.*,tb_m_user.email as email_notaris');
$this->db->from('tb_m_notaris');
$this->db->join('tb_m_user', 'tb_m_user.id=tb_m_notaris.id');
$this->db->where('tb_m_notaris.id', $id);
$query = $this->db->get();
return $query->result_array();
}
You need to update your query to this.
As id column exists in both the tables, you need to explicitly provide which table id you want to connect to by mentioning the table name.
Related
How can I get the last inserted id
I use the following code which works:
DB::insert("INSERT INTO members (name,email)values($name,$email)");
$lastID = DB::getPdo() -> lastInsertId();
But the following code doesn't give me the last inserted id.
DB::transaction(function () {
$result = DB::insert("INSERT INTO members (name,email)values($name,$email)");
$lastID = DB::getPdo() -> lastInsertId();
}, 5);
return $lastID;
Even when I use the variable($lastID) outside the transaction it still doesn't work.
What am I doing wrong here?
When using the query builder, Laravel has the function insertGetId which inserts the row and returns the newly created id.
$lastid = DB::table('members')->insertGetId(['name' => $name, 'email' => $email]);
Please see sample code below. Hope it helps.
public function testModel($data) {
$id = DB::transaction(function() use ($data) {
$record_id = DB::table('users')->insertGetId($data);
DB::update('update users set votes = 100 where name = ?', ['John']);
return $record_id;
});
return $id; // this will return the last inserted id which is the $record_id inside the DB::transaction
}
You can get it easily:
$last_id = DB::table('members')->insertGetId(['name => $name, 'email => $email]);
this worked for me
public function testModel($data) {
$last_id = DB::transaction(function() use ($data) {
Table::create($data);
return DB::getPdo()->lastInsertId();
});
return $last_id; // this will return the last inserted id
}
The trick should be quite simple if you use Model. Let's assume you've Member model. So when you try to insert record it returns the inserted record in response.
/** Insert record **/
$member = Member::create(['name' => $name, 'email' => $email])
/** your last inserted id will be in $member **/
$lastInsertedId = $member->id
Hope this works for you.
I am trying to return customers from model Customer where id < 10. I do have some in the database.
$customers = Customer::where('id', '<', 10)->get();
return json_encode(['customers' => $customers]);
The above code will error out "Trailing data"
and when I try to dd($customers), I get a list of the collection Customer
I have no idea why I keep getting that and why the model is returning raw collection and not an object of the list of customers???
It seems like a null date "updated_at" field is causing the error. don't know why!
Solved By:
on the Customer model I had to do:
//ask Laravel to not manage default date columns
public $timestamps = false;
also I to mutate those columns:
public function setDateRemindedAttribute($value)
{
if (strlen($value)) {
$this->attributes['date_reminded'] = Carbon::createFromFormat('d/m/Y', $value);
} else {
$this->attributes['date_reminded'] = null;
}
}
public function setUpdatedAtAttribute($value)
{
if (strlen($value)) {
$this->attributes['updated_at'] = Carbon::createFromFormat('d/m/Y', $value);
} else {
$this->attributes['updated_at'] = $_SERVER['REQUEST_TIME'];
}
}
Use response()->json() like this
$customers = Customer::where('id', '<', 10)->get();
return response()->json(['customers' => $customers]);
How do I use a custom query in a model using the yii2 framework? I am trying but errors occurs.
I am a beginner in Yii2 Framework.
Here is my login model:
public function getUser($id)
{
$return = User::findBySQL("Select * from User where userType = 'AHP' and userid = '$id';");
return($return['AHPName']);
}
findOne()
Returns a single active record model instance by a primary key or an
array of column values.
$data = User::findOne(['userType' => 'AHP', 'userid' => $id]);
This will find the user whose user type is AHP and whose userid is $id.
public function getUser($id)
{
$data = User::findOne(['userType' => 'AHP', 'userid' => $id]);
return $data['AHPName'];
}
Try with ActiveQuery:
public function getUser($id)
{
$data = User::find()->where(['userType' => 'AHP', 'userid' => $id])->one();
return $data['AHPName'];
}
using custom queries:
public function getUser($id)
{
$sql = "Select * from User where userType = 'AHP' and userid = '.$id.'";
$return = User::findBySQL($sql)->one();
return $return->AHPName;
}
you can try this technique for writing a custom query in yii2
<?php
use yii\db\Query;
$query = new Query();
$query->select(['*'])->from('user')
->where('user.userType=:id',['id'=>'AHP'])
->andWhere('user.userid=:no',['no'=>$id]);
$command = $query->createCommand();
$result = $command->queryAll();
?>
another to do this
User::find()->where('userType = :type and userid = :id',
['type'=>AHP, 'id' => $id])->one();
In controller i have:
public function actionGetItems()
{
$model = new \app\models\WarehouseItems;
$items = $model->find()->with(['user'])->asArray()->all();
return $items;
}
In WarehouseItem model i have standard (created by gii) relation declaration:
public function getUser()
{
return $this->hasOne('\dektrium\user\models\User', ['user_id' => 'user_id']);
}
How can i control which column data do i get from "user" relation? I currently get all columns which is not good as that data is being sent to Angular in JSON format.
Right now i have to loop trough $items and filer out all columns i dont want to send.
You should simply modify the relation query like this :
$items = \app\models\WarehouseItems::find()->with([
'user' => function ($query) {
$query->select('id, col1, col2');
}
])->asArray()->all();
Read more : http://www.yiiframework.com/doc-2.0/yii-db-activequerytrait.html#with()-detail
Your code should go this way.
public function actionGetItems()
{
$items = \app\models\WarehouseItems::find()
->joinWith([
/*
*You need to use alias and then must select index key from parent table
*and foreign key from child table else your query will give an error as
*undefined index **relation_key**
*/
'user as u' => function($query){
$query->select(['u.user_id', 'u.col1', 'u.col2']);
}
])
->asArray()
->all();
return $items;
}
Inside WarehouseItem model
/**
* #return ActiveQuery
*/
public function getUser()
{
$query = User::find()
->select(['id', 'col1', 'col2'])
->where([
'id' => $this->user_id,
]);
/**
* Default hasOne, setup multiple for hasMany
* $query->multiple = true;
*/
return $query;
}
I'm using Laravel 4 and I need to take entries from my database, put them into an array and use them in a foreach loop in my view.
I'm not getting any errors but I'm also not getting anything from the database.
I'm trying to edit this page of a Laravel bundle to get products from the database, rather than statically.
This is my query from my Model
return $products = \DB::select('select * from products', array('sku', 'name'));
Controller...
public function getIndex()
{
// Get the products.
//
$products = Products::all();
// Show the page.
//
return View::make('shpcart::home')->with('products', $products);
}
This is my view
<pre>
<?php
print_r($products);
?>
</pre>
This is the result
Array
(
)
This works to insert into the database:
DB::insert('insert into products (sku, name) values (?, ?)', array('WS004', 'Test'));
This...
$products = DB::table('products')->get();
foreach ($products as $product)
{
echo $product->sku;
}
returns the error
Invalid argument supplied for foreach()
You can see it here...
http://wilsonswan.co.uk/collection
Thanks in advance.
You should not return $products as such.
You should perhaps do something like:
public function index()
{
$products = Products::where('sku', '=', 'name')->get();
return View::make('view', compact('products'));
}
try this:
public function getIndex() {
$db = DB::table('products as p')
->where('p.sku', '=', 'WS004');
$products = $db->get();
return View::make('shpcart::home')
->with('products', $products);
}