laravel 5.1 filter using pivot table - many-to-many

Hi i am developing job portal but facing a problem in pivot table filtering. i have a table like below
personal_details
id
name
sex
dob
nationality
visa_status
vacancies
id
name
description
created_at
updated_at
which have a many-to-many relation with pivot table.
Data here is inserted when a job-seeker apply for a vacancy
personal_detail_vacancy
id
personal_detail_id
vacancy_id
created_at
updated_at
PersonalDetail model
class PersonalDetail extends Model
{
public function vacancies()
{
return $this->belongsToMany('App\Vacancy')->withTimestamps();
}
}
Vacancy model
class Vacancy extends Model
{
public function personal_details()
{
return $this->belongsToMany('App\PersonalDetail');
}
what i want to do is select all personal detail who have applied for a job(in any vacancies) in a particular date
i tried
$personal_details = PersonalDetail::with(array('vacancies' => function($query){
$query->wherePivot('created_at', '2015-11-10 11:33:24');
}))->get();
but it is not filtering the date
ANY IDEA?

well solved this by using
$personal_details = PersonalDetail::whereHas('vacancies',function($query)
{
$query->where('created_at','2015-11-10 11:33:24');
})->get();
it was not working before. The problem was i had 'created_at' field in vacancies table also.

Related

how to get id from joined table sql

I have a joined table from siswa and kelas. in kelas table there is a column idSiswa, it comes from id from siswa table. the question is how I can get the id from kelas when its joined. when I try to fetch id it shows the id from siswa table, not from kelas table, I also already used right join and left join and still not get the answer
this is my kelas table
this is my siswa table
I using a query builder from laravel to run the query, and this is my query
$siswa = DB::table('siswas')
->join('kelas', 'kelas.idSiswa', '=', 'siswas.id')
->where([
['kelas.kelas', '2'],
['kelas.semester', 'ganjil'],
])
->select('kelas.*', 'siswas.*')
->get();
Your issue comes from a name conflict. When you join your two tables, there are 2 fields. To solve it, you should use SQL alias.
You can see an example on this topic
You could also consider using Eloquent which offers OOP advantages and automatically avoids this kind of issues.
namespace App;
use Illuminate\Database\Eloquent\Model;
class Kelas extends Model
{
public function siswa()
{
return $this->belongsTo('App\Siswa', 'idSiswa', 'kelas');
}
}
namespace App;
use Illuminate\Database\Eloquent\Model;
class Siswa extends Model
{
public function kelas()
{
return $this->hasMany('App\Kelas', 'idSiswa', 'kelas');
}
}
$siswa = App\Siswa::with('kelas')
->where([
['kelas', '2'],
['semester', 'ganjil'],
])
->get();
$firstSiswaKelasIds = $siswa->first()->kelas->map->id;

fetching data from three tables in laravel

The is the table structure,which basically has three tables,namely expenses,categories and sunbcategories
table expenses
(id,category_id,sub_category_id,date,description,amount)
table categories
(id,category_name)
table subcategories
(id,sub_category_name,category_id)
This is the SQL query that is needed
select expense.date, expense.description, expense.amount,
category.category_name, subcategory.sub_category_name
from expenses as expense,categories as category,subcategories as subcategory
where expense.category_id=category.id and
category.id=subcategory.category_id);
This is the function in Expense model with which I pass the category_id
The same query mentioned above is written in laravel, but I am not able to
fetch the data.
function fetchExpenseData($categoryId)
{
$expense = Expense::select("expenses.*","categories.category_name as
Categoryname","subcategories.Sub_category_name")
->join("categories","categories.id","=","expenses.category_id");
->join("subcategories",function($join)
{
$join>on("subcategories.category_id","=","expenses.category_id")
->on("suncategories.id","=","expenses.sub_category_id")
})->get();
return $expenses;
}
$expenses that are returned will be printed in blade.php.
Can I know what is the mistake
thanks in advance
Hye there ,
You need to add eloquent model for retrieving data fromenter code here three tables
Like
I have School Table , Student Table , Teacher Table
School is relating with both Student and Teacher then we will add relationship
In School Model
`
public function getStudent(){
return $this->hasMany('student_id' , App\Student);
}
public function getTeachers(){
return $this->hasMany('teacher_id' , App\Teacher);
}
In Student table
public function getSchool(){
return $this->hasOne('school_id' , App\School);
}
`
now call data from student
`
$students = Student::with('getSchool.getTeachers')->get()
This Demonstration for what I have get from your Question

How to fetch records from two different tables in laravel5.2

I have two tables 'approval' and 'renewal', both having a common column 'applicant_id'.
When new application comes-in, it stores a data-record in table 'approval' alongwith the 'applicant_id' for whom the record has been added.
Now, when there is a renew applied for that same applicant, the row gets created in the table 'renewal' referencing the 'applicant_id'
Note: There can be a single record in the table 'approval' for a 'applicant_id' but there can be more than one record for the same 'applicant_id' in the table 'renewal'.
Now, my requirement is:
I need to fetch the records from both the table for all the applicants.
Conditions: If there is a data for the 'applicant_id' in both the table and 'renewal' table has multiple row for the same 'applicant_id', then I need to get the records from 'renewal' table only that too the latest one.
If there is no data in 'renewal' table but exists in 'approval' table for the 'applicant_id', then the fetch record should get the data present in 'approval' table.
Basically, if there is record for the applicant in 'renewal' table, get the latest one from there, if there is record present only in 'approval' table, then get that one but the preference should be to get from 'renewal' if exists.
I am trying to do this in laravel 5.2. So, is there anyone who can help me in this?
If you're using Eloquent, you'll have 2 models:
Renewal.php
<?php
namespace App;
use Illuminate\Eloquent\Model;
class Renewal extends Model
{
protected $table = 'renewal';
public static function findMostRecentByApplicantId($applicantId)
{
$applicant = self::where('applicant_id', '=', $applicantId)
->orderBy('date_created', 'desc')
->first();
return $applicant;
}
}
Approval.php
<?php
namespace App;
use Illuminate\Eloquent\Model;
class Approval extends Model
{
protected $table = 'approval';
public static function findByApplicantId($applicantId)
{
$applicant = self::where('applicant_id', '=', $applicantId)
->first();
return $applicant;
}
}
Then, in the code where you want to get the approval/renewal record, use the following code:
if (! $record = Renewal::findMostRecentByApplicantId($applicantId)) {
$record = Approval::findByApplicantId($applicantId);
}
//$record will now either contain a valid record (approval or renewal)
//or will be NULL if no record exists for the specified $applicantId
After few try, I got one way to do it using raw:
SELECT applicant_id, applicant_name, applicant_email, applicant_phone, renewed, updated_at
FROM (
SELECT renewal_informations.applicant_id, renewal_informations.applicant_name, renewal_informations.applicant_email, renewal_informations.applicant_phone, renewal_informations.renewed, renewal_informations.updated_at
FROM renewal_informations
UNION ALL
SELECT approval_informations.applicant_id, approval_informations.applicant_name, approval_informations.applicant_email, approval_informations.applicant_phone, approval_informations.renewed, approval_informations.updated_at
FROM approval_informations
) result
GROUP BY applicant_id
ORDER BY applicant_id ASC, updated_at DESC;
For every single Approval id, there can b multiple records for renewal table suggests you have One to Many relation. which you can define in the your Model like
Approval.php (App\Models\Approval)
public function renewal()
{
return $this->hasMany('App\Models\Renewal', 'applicant_id')
}
Having defined this relation. you can get the records from the table using applicant_id.
$renewal_request_records = Approval::find($applicant_id)->renewal();
This will get all records from renewal table against that applicant_id.
Finding the latest
$latest = Renewal::orderBy('desc', 'renewal_id')->first();
Further Readings Eloquent Relations

Nested Query in laravel

I have two tables:
Table 1: tbluser
ID Name
1 .......... name1
2 .......... name2
3 .......... name3
Another table that links tbluser and tblrole
Table2: tbllinkuserrole
userid..........roleid
1 ............2
1 .......... 2
1 .......... 2
2 .......... 2
3 .......... 1
I would like to fetch the tbluser.Name and the user role from tbllinkuserrole in to a table: a single table row(user record) can have multiple rows inside the column 'role' based on the roles fetched from tbllinkuser role. A user can have multiple roles.
can you help me out...
Laravel have Models (Eloquent), in the model class are some functions that are easy to user to fetch data from table. (this works with Laravel 5.2)
The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table. https://laravel.com/docs/5.2/eloquent
So first of all, you need a User model (php artisan make:model User). You need to link the User modal to the right table.
//File: /laravel/app/User.php
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected $table = 'tbluser';
public function userRoles() {
//Get the table data with the user roles
$this->hasMany('App\UserRoles', 'user_id', 'id');
//First argument gets the UserRoles Modal
//Second argument get the UserRoles column 'user_id'
//Third argument get the User table - column id
}
//File: /laravel/app/UserRoles.php
use Illuminate\Database\Eloquent\Model;
class UserRoles extends Model
{
protected $table = 'tbllinkuserrole';
public function rank() {
//Get the table data with role
$this->hasOne('App\Roles', 'id', 'role_id');
//First argument gets the Roles Modal (table)
//Second argument get the Roles column 'id'
//Third argument get the UserRoles modal (table) - column role_id
}
//File: /laravel/app/Roles.php
use Illuminate\Database\Eloquent\Model;
class Roles extends Model
{
protected $table = 'tblroles';
}
Now if you call Auth::user()->userRoles you will get an array with all rows from table that are linked to the current user.
And when you're running this you dump all the user rank data.
foreach(Auth::user()->userRoles as $userrole) {
{{ dump($userrole) }}
{{ dump($userrole->rank) }}
}
I hope this works for you!
More information can be found on https://laravel.com/docs/5.2/eloquent
TRY THIS ONE
SELECT tbllinkuserrole.userid, tbllinkuserrole.roleid, tbluser.name
FROM tbllinkuserrole, tbluser
WHERE tbllinkuserrole.userid = tbluser.id
The mysql to get the row values as column,
SELECT U.id, U.Name, MAX(CASE WHEN R.roleid = 1 THEN R.roleid END) role_1, MAX(CASE WHEN R.roleid = 2 THEN R.roleid END) role_2 from table_c AS U LEFT JOIN table_b AS R on (U.id = R.userid) WHERE 1 GROUP BY U.id

Display created_at from pivot table in Laravel 4

I have a three tables - attendees, messages and attendee_message. When a users is sent a standardized message a record is added to the pivot table attendee_message with the id of the attendee, the id of the message and a date/time stamp in the created_at field.
My issue is that both the attendees and messages tables have a field called created_at and when I go to display the date/time the message was sent (the created_at from the attendee_message column) it displays the created_at from the messages table. How do I display the created_at from the attendee_message table instead?
The function that gets the attendees, a scope and the relationship from the model:
public function getatts() {
$atts = Attendee::cmo()->orderBy('created_at');
$atts = $atts->paginate(25);
return $atts;
}
public function scopeCmo($query)
{
return $query->where('block_id', '=', 3);
}
public function messages() {
return $this->belongsToMany('\App\Models\Message','attendee_message','attendee_id','message_id')
->withPivot('id');
}
From my list.blade.php:
#foreach ($att->messages as $message)
<li>'{{$message->subject}}' sent {{$message->created_at}}</li>
#endforeach
To access the row in the pivot table you can use the pivot property. Laravel docs
$message->pivot->created_at
However, by default there are only keys present in the pivot object. So you will need to do
->withPivot('created_at');
on the relationship. In your case it would be ->withPivot('id', 'created_at') if you want to have id in there as well