where condition in Codeigniter - mysql

i am trying to fetch data from the table which has some foreign keys by using codeigniter's active records. i haven't get any result. my question is where i'm going wrong here is my code in model.
public function fetch_customer()
{
$s = 'customer.stb_id';
$w_array = array('set_top_box.stb_id' => $s );
$customers = $this->db->select('customer.c_name,customer.acc_no,customer.stb_id,set_top_box.stb_no,customer.mobile_no,customer.subscription_amount,customer.c_status')
->from('customer,set_top_box')
->where($w_array)
->get();
return $customers->result();
}

Hello you can not add multiple table name in form () clause you use join() like this
public function fetch_customer()
{
$s = 'customer.stb_id';
$w_array = array('set_top_box.stb_id' => $s );
$customers = $this->db->select('customer.c_name,customer.acc_no,customer.stb_id,set_top_box.stb_no,customer.mobile_no,customer.subscription_amount,customer.c_status')
->from('customer')
->join('set_top_box','here on clause ')
->where($w_array)
->get();
return $customers->result();
}

Related

Is it possible to combine whereHas with 'or' queries?

I'm trying to implement a filter system where, among other attributes and relationships, items are categorized. However, the challenge appears when combining OR queries with other filters using the regular and clause. The result grabs rows which I do not want and adds the or when the condition for that fails, thus polluting the final results with unwanted data.
<?php
class ProductSearch {
public $builder;
private $smartBuild; // this is the property I'm using to disable the alternation when other search parameters are present to avoid polluting their result
function __construct( Builder $builder) {
$this->builder = $builder;
}
public function applyFilterToQuery(array $filters) {
$pollutants = ['subcategory', 'subcategory2', 'category'];
$this->smartBuild = empty(array_diff( array_keys($filters), $pollutants)); // [ui=>9, mm=>4], [mm]
foreach ($filters as $filterName => $value) {
// dd($filters, $filterName );
if (method_exists($this, $filterName) && !empty($value) )
$this->$filterName( $value);
}
return $this;
}
public function location( $value) {
$this->builder = $this->builder
->whereHas('store2', function($store) use ($value) {
$store->where('state', $value);
});
}
public function subcategory( $value) {
$name = Subcategories::where('id', $value)->pluck('name');
$this->builder = $this->builder->where('subcat_id', $value);
if ($name->isNotEmpty() && $this->smartBuild) {
$names = preg_split('/\W\s+/', $name[0]);
if (!$names) $names = $name;
foreach ($names as $value)
$this->builder = $this->builder->orWhere('name', 'like', "%$value%");
}
}
}
You may observe from the above that making a request for categories searches products matching the category name. But on attempting to combine that alternate match with legitimate AND queries (in location for instance, the result tends to include matching locations OR matching names.
The desired result is ((matching name OR matching category) AND matching location). Is this possible?
I had similar situation like this few days ago about User and Posts.
Needed a list of posts which user has commented or participated in and which user owns.
So I did following on User model
//Get user created post or if user has participated in the post
$queryString->where(function ($query) use ($user_id) {
return $query->whereHas('participants', function ($q) use ($user_id) {
$q->where('user_id', $user_id);
})->orWhere('id', $user_id);
});
Hope this helps.

Database Error When trying to Join Table Codeigniter

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.

How to fetch data from single column stored in array using laravel?

I need to fetch the each and every column individually from the field array_payout can anyone solve it
$currentMonth_start_Date = Carbon::now()->startOfMonth()->subMonth(1);
$currentMonth_end_date = Carbon::now()->subMonth()->endOfMonth();
$clients_referral_tree = DB::table('mam_referral_payout')
->select('clients.id', 'mam_referral_payout.*')
//->addSelect(DB::raw('SUM(mam_referral_payout.Final_amount) as referral_amount'))
->leftjoin('clients', 'clients.id', '=', 'mam_referral_payout.to_id')
->where('clients.id', '=', (Auth::user()->id))
->whereBetween('mam_referral_payout.created_at', [$currentMonth_start_Date, $currentMonth_end_date])->get();
$clientTree = [];
foreach ($clients_referral_tree as $tree) {
$clientThree = $tree;
$clientTree[] = $clientThree;
}
dd($clientTree);
You can add the following to your Model:
protected $casts = [
"array_payout" => "object"
];
Add an accessor for each attribute in your json like this for example:
public function getTotalAmountAttribute(){
return optional($this->array_payout)->total_amount;
}
You can use them like this:
$clientTree1->total_amount;

how to get recently affected rows attribute in model of codeigniter

primary key of title table is id and it is an auto-increment when I insert data to the table I need to return the id of currently inserted row.
my model function is,
function addDate($x, $y, $z) {
$sql = "INSERT INTO title (title,no,user) VALUES ('$x','$y','$z')";
$query = $this->db->query($sql );
if($this->db->affected_rows() > 0) {
return "ok";
} else {
return "err";
}
}
Please help me on this.
You are wrong. In your function you are getting these three parameters ($x, $y, $z) But in code you are Inserting ('$t','$n','$a')(Question is edited)
Use $this->db->insert_id() to get last insert id
Try this
function addDate($x, $y, $z) {
$data = array(
'title' => $x ,
'no' => $y ,
'user' => $z
);
if(!$this->db->insert('title', $data)){
return FALSE ;
}
else{
$lastId = $this->db->insert_id(); # add this
return $lastId;
}
}
FYI: Don't use $x, $y, $z. use meaningful names like $title, $no, $user
Codeigniter Active Record Class Version 2.2.0

Laravel 4 MySQL query to array?

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);
}