cannot make relation in codeigniter - php

I want to make a relation table in table pelatih and table absen. But when I try to make a relation id_pelatih it always input number "3".
This is the controller:
function absen()
{
$this->load->library('user_agent');
$nim = $this->uri->segment(4);
$id_user = $this->session->userdata('user_id');
$id_pelatih = $id_pelatih;
$this->load->model('mabsensi');
$data = array(
'id_pelatih' => $this->mlogin->get_data_pelatih_by_id_user($id_user)->id_pelatih,
'nim' => $nim,
'tanggal' => date('Y-m-d H:i:s'),
'keterangan' => 'Hadir'
);
$this->mabsensi->insert_absensi($data);
redirect($this->agent->referrer());
}
This is the model
function get_data_pelatih_by_id_user($id_user)
{
$this->db->select('*')
->from('pelatih as a, user as u')
->where('a.id_user = u.id_user')
->limit(1);
return $this->db->get()->row();
}
Please tell me how to solved this.

Your model isn't correct. If you want to get data from different tables you should use JOIN. And you have to say which record you need. So, add a WHERE statement to your query.
function get_data_pelatih_by_id_user($id_user)
{
$this->db->SELECT('*')
->FROM('user')
->WHERE('id_user', $id_user) // your parameter, you did not use it
->JOIN('pelatih', 'pelatih.id_user = user.id_user');
return $this->db->get();
}
Also have a look at the documentation: http://ellislab.com/codeigniter/user-guide/database/active_record.html

Related

How to query two tables in Laravel

I am trying to query two tables in Laravel when the user submits a form. The data is stored in the transaction table and I can also update the Account table by adding the $transactions->amt with $account->total.
I tried doing this;
public function store(Request $request)
{
$account = DB::table('users')
->join('accounts', "users.id", '=', 'accounts.user_id')
->select('users.*', 'accounts.*')
->first();
$transaction = new Transaction();
$data = $this->validate($request, [
'baddress'=>'required',
'package'=>'required',
'amt'=>'required',
]);
$transaction->username = $account->username;
$transaction->baddress = $request->input('baddress');
$transaction->package = $request->input('package');
$transaction->amt = $request->input('amt');
$transaction->fund_option = "Fund";
$transaction->save();
$bal= $transaction->amt + $account->total;
$account->amt_paid = $bal;
$account->total = $bal;
$account->save();
return redirect('/transfer')->with('success', 'Transaction has been made');
}
but I got this error:
Call to undefined method stdClass::save()
How can I find the best method to do this?
That error occur because $account is not collection. method save() is method from model collection.
if you want update you can use this code like.
$accountUpdate = DB::table('accounts')
->where('id', $account->id)
->update(['amt_paid' => $bal, 'total' => $bal]);
but if you want to use method save() then you have to call $account from model.
$account is a row made by your join (users.* and accounts.*) so it's a stdClass, not an Eloquent model. You don't have a save() method
in order to do this you should have a relationship between User model and Account model:
//Account.php
public function user(){
return $this->belongsTo("App\User");
}
........
//User.php
public function account(){
return $this->hasOne("App\Account");
}
then you can retrieve Account from your User:
$user = User::first();
$account = $user->account;
[....]
$account->amt_paid = $bal;
$account->total = $bal;
$account->save();
You have to use like this. This is simple as like as much
$accountModelUpdate = DB::table('accounts')
->where('user_id', $account->id)
->update(['amt_paid' => $bal, 'total' => $bal]);

Putting order by inside with(), in Laravel

I have a controller that filters the columns in it's table based on the variable received in the get query, then it returns it with another table's value based on the id of the variable gotten, But now for the $filter_by_name condition I want to filter by the first_name column in the users table, please how can i do that, i.e I want to return the users table ordered by their first_name column
DB-STRUCTURE
COMPANY-USERS TABLE
id company_id user_id role created modified active department_level
USERS TABLE
id
first_name
last_name
email
password
active_company
profile_photo_id
verified
active
remember_token
created
modified
Company-users Controller
public function getCompanyUsers($companyId)
{
$filter = strtolower(Input::get('filter'));
if($filter && $filter === 'on' ){
$filter_by_date = strtolower(Input::get('filter_by_date'));
$filter_by_name = strtolower(Input::get('filter_by_name'));
$filter_by_role = strtolower(Input::get('filter_by_role'));
if($filter_by_date){
if($filter_by_date == 'oldest'){
$users = CompanyUser::where('company_id', $companyId)->orderBy('created', 'DESC')
->with(['user','user.userDepartments','user.userDepartments.department'])->get();
return $users;
}else{
$users = CompanyUser::where('company_id', $companyId)->orderBy('created', 'ASC')
->with(['user','user.userDepartments','user.userDepartments.department'])->get();
return $users;
}
}elseif ($filter_by_name){
if($filter_by_name == 'ascending'){
$users = CompanyUser::where('company_id', $companyId)->orderBy('first_name', 'ASC')
->with(['user','user.userDepartments','user.userDepartments.department'])->get();
return $users;
}else{
$users = CompanyUser::where('company_id', $companyId)->orderBy('first_name', 'DESC')
->with(['user','user.userDepartments','user.userDepartments.department'])->get();
return $users;
}
}elseif($filter_by_role){
if($filter_by_role == 'member'){
$users = CompanyUser::where(['company_id' => $companyId,'role'=>'Member'])->with(['user','user.userDepartments','user.userDepartments.department'])->get();
// dd($users);
return $users;
}elseif($filter_by_role == 'manager'){
$users = CompanyUser::where(['company_id' => $companyId,'role'=>'Manager'])->with(['user','user.userDepartments','user.userDepartments.department'])->get();
return $users;
}else
$users = CompanyUser::where(['company_id' => $companyId,'role'=>'Admin'])->with(['user','user.userDepartments','user.userDepartments.department'])->get();
return $users;
}
}
$users = CompanyUser::where('company_id', $companyId)->
with(['user','user.userDepartments','user.userDepartments.department'])->get();
//dd($users);
return $users;
}
you can pass closer functions when eager loading to add constrains like that, see more on laravel docs:
$users = CompanyUser::with(['user'=> function ($query) {
$query->orderBy('first_name', 'desc');
}
])
->where('company_id', $companyId)
->get();
You have to do orderBy on a relational model like below:
$users = CompanyUser::where('company_id', $companyId)
->with(['user' => function($subQuery){
$subQuery->orderBy('first_name', 'ASC');
}])
->with(['user.userDepartments','user.userDepartments.department'])
->get();
return $users;
One way is to add column 'first_name' in the 'COMPANY-USERS' TABLE
And now you can do order by ('first_name','ASC').
I think its not the best way but no other idea comes in my head.

I cannot fetch data from using this code

public function orderView(Request $request){
$orderByID = $request->id;
$orderDetailsView = DB::table('order_details')
->where('order_id',$orderByID)
->get();
return view('admin.order.vieworder', ['orderDetailsView' => $orderDetailsView]);
}
If i return only $orderByID it shows the id. But using this id i cannot fetch data from the database table. it shows empty array.
Try this code
$orderss = DB::table('order_details')->where('order_id', '=', $orderByID)->get();

Laravel - Comparing a database value with a variable

I have a basic appointment system set up, however everybody logged in can see all appointments, so what I'm trying to do is make it so users can only see their appointments. To do this I'm trying to get the logged in users Id then display all the appointments that have this user_id value (Appointments is a junction table)
I know my code is probably awful but any help is appreciated, thanks
function index()
{
$logged_user_id = Auth::user()->id;
$user = User::find($logged_user_id);
$appointments = Appointment::where('user_id', '=' $user)->get();
return view ('appointment/userappointments',['appointments' => $appointments]);
// $appointments = Appointment::all();
}
Set up your model relations and you can just do this
function index()
{
$appointments = Auth::user()->appointments;
return view ('appointment/userappointments',['appointments' => $appointments]);
}
You already have the user id, dont have to fetch User info.
function index()
{
$logged_user_id = Auth::user()->id;
$appointments = Appointment::where('user_id', '=' $logged_user_id)->get();
return view ('appointment/userappointments',['appointments' => $appointments]);
//$appointments = Appointment::all();
}

Selecting required fields using relations in Laravel

I have a model Meetings like this:
public function meeting_comments(){
return $this->hasMany('App\MeetingsComments', 'meeting_id', 'id');
}
public function meeting_users() {
return $this->hasMany('App\UserMeetingDetails', 'meeting_id', 'id');
}
The Controller is like this:
$res = Meetings::with('meeting_comments', 'meeting_users')
->select('')->get()->toArray();
I only need comments from meeting_comments and user_id from meeting_users.
What do I put in select to only get the required fields from meeting_comments and meeting_users ??
You do it through a closure in the with call:
$res = Meetings::with(['meeting_comments' => function($query) {
$query->select('comments', 'meeting_id');
}, 'meeting_users' => function($query) {
$query->select('user_id', 'meeting_id');
}])
->get()->toArray();
I'm taking this from memory, so the syntax may be slightly incorrect, but it should work. :)

Categories