this is my campus model
i have stripped the models for readability
and of course there is join table named as campus_user with id, campus_id, user_id
users can subscribe to campuses
now i want 2 things
1. Get all the users subscribed to a specific campus
2. Check to see if a specific user ( say with id = 1 ) is subscribed to a specific campus ( say with id = 2 )
class Campus extends \Eloquent{
protected $table = "campuses";
public function users(){
return $this->belongsToMany("User");
}
}
// this is my user model
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $table = 'users';
protected $hidden = array('password', 'remember_token');
public function campuses(){
return $this->belongsToMany('\Models\Campus');
}
}
Well the most "Eloquent like" way would be using relationship querying:
http://laravel.com/docs/4.2/eloquent#querying-relations
A simple example would be returning users with any campuses.
// Get users with any campus relationship.
$users = User::has('campuses')->get();
However you need something more powerful.
For 'users' in a specific 'campus'.
// Get 'users' in a 'campus' where the 'name' column equals 'foo'.
$campus = 'foo';
$users = User::whereHas('campuses', function($query) use ($campus) {
$query->where('name', $campus);
})->get();
For a specific 'user' in a specific 'campus' the code would almost be the same.
// Find the 'user' with a primary key of '1' in the 'campus' where
// the 'name' column equals 'foo'.
$primaryKey = 1;
$campus = 'foo';
$users = User::whereHas('campuses', function($query) use ($campus) {
$query->where('name', $campus);
})->find($primaryKey);
As you can see the last example replaced the get() method from the previous example.
You can do the same with the callback in the whereHas() method when you want to query using the primary key. This would result in the following.
...
$query->find($campus);
...
All the methods described above can be found in the Illuminate\Database\Eloquent\Builder class.
I would recommend taking a look at some of the source files to get a better understanding how request are handled.
Related
I have three models with some methods like
1.Employee Model
class Employee extends Model
{
protected $fillable = [
'employee_no','card_no','inactivedate', 'activedate', 'status',
];
public function office(){
return $this->hasOne(EmployeeOffice::class);
}
public function section(){
return $this->belongsTo('App\Hrm\Section');
}
}
2.EmployeeOffice Model
class EmployeeOffice extends Model
{
$fillable = ['employee_id','section_id','line_id','join_date','gross','confirm_date'];
public function employee(){
return $this->belongsTo(Employee::class);
}
public function section(){
return $this->belongsTo('App\Hrm\Section');
}
}
3.Section model....
class Section extends Model
{
protected $fillable = ['name','description','status'];
//
}
i need all inactive employee information according to the employee inactive date(from employee model) as well as their all office information from EmployeeOffice model and must be groupBy according to section_id which is (section_id as foreign key) available in EmployeeOffice model.
For that i have to go with some condition like ..
Employee::where('inactivedate','like','%'.$date.'%');
*And need all data from office and employee table
*need section name and grouped by as section name from section model
***please suggest me how can i solve this problem ***
Try this:
$data = Section::with(
array(
'employeeOffice' => function(
$query->with(
'employees' => function(
$query->where('employees.inactivatedate', 'like', '%'.$date.'%'
)
)
)
)
)
->get();
This should give you an array to every section_id. In this array are the employeeOffices (1:n-Relationship). The second query with with will fetch for each employeeOffice the employee who sits in it.
But if you defined the relationships right, this should do the trick to:
Section::with('EmployeeOffice.Employee')->get();
Nested Eager Loading
I have solved my problem by this...
if(Input::has('start') && Input::has('end')){
$start = Carbon::parse(Input::get('start'))->startOfDay();
$end = Carbon::parse(Input::get('end'))->endOfDay();
$start = $start->format('Y-m-d');
$end = $end->format('Y-m-d');
EmployeeOffice::query()->whereHas('employee',function ($query) use ($start,$end){
$query->whereBetween('inactivedate',[$start, $end])->where('status',0);
})->paginate()->groupBy('section_id');
}
I want to join three tables. Here is the DB model in server:
lecturers
id - integer (PK)
......
examination
id - integer (PK)
.....
exam_supervision
lecturer_id - integer (FK)
exam_id- integer (FK)
Model relation as I implemented in laravel.
```
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Examsupervision extends Model {
public $timestamps = false;
protected $table = 'exam_supervision';
protected $fillable = ['lecturer_id', 'exam_id'];
}
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Examination extends Model {
public $timestamps = false;
protected $table = 'examination';
protected $fillable = ['name', 'module_id', 'startdate', 'enddate', 'duration', 'type', 'code', 'status'];
}
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Lecturers extends Model {
public $timestamps = false;
protected $table = 'lecturers';
protected $fillable = ['user_id', 'address', 'phone'];
}
```
lecturers, examinations and exam_supervision which is M:M. What I want is find all the examinations of a lecturer.
My code
public function lecturerViewExaminations($id)
{
what code to get all exam for a lecturer..say ID 129
}
Returning me empty set. WHat am I doing wrong? It is easy in SQL syntax but in laravel I am finding it very confusing
What i understand from your question is:
You have one model (Examsupervision) and want the relations examinations and lectures
You can use Eloquent: Relationships
First create a model. In this case your model name would be something like Examsupervision.
In your model(Examsupervision) you can define your relations. In this case examinations and lextures
Create for every relation a new model. So you will have 3 models (Examsupervision, Examinations, Lectures).
Now in your model Examsupervision create a new relation function.
public function lectures()
{
return $this->hasMany('App\Lectures');
}
public function examinations(){
return $this->hasMany('App\Examinations');
}
In your database table "lectures" and "examinations" create a new key with the name examsupervision_id. This key will be the id of the Examsupervision row.
Now in your code when you want the get all the lectures of a given Examsupervision you can do this.
$examsupervision = Examsupervision::find($id); //$id = the Examsupervision you want to retrieve
$lectures = $examsupervision->lectures; //This will return all the lectures connected to examsupervision
And for examinations you can do the same with:
$examsupervision = Examsupervision::find($id); //$id = the Examsupervision you want to retrieve
$examinations = $examsupervision->examinations;
Hope this helps
You are missing ->get() after the last where.
$examinations= Examsupervision::with('lecturers', 'examinations')->where('lecturer_id', 'id')->where('exam_id', 'id')->get();
Model::with() is for relation, Use just ->get()
$examinations=Examsupervision::with('lecturers', 'examinations')->get();
You already have relation for lecturers and examinations.
If not worked, share Model Examsupervision
Been learning laravel for 4 days and im trying to fix this error for 2 hours and i cant still fix it. I can save on one to many relationship but i cant retrieve data i think there something wrong with the relationship. Im trying to retrieve posts on user using this line but im getting not empty results on users but empty result on posts. Same thing happening on categories and posts which is many to many relationship but i cant save on many to many.
$users = User::with('posts')->get();
ANd im getting an error when i use this the error is
Undefined property: Illuminate\Database\Eloquent\Collection::posts()
$users = User::where('user_id','=','2')->get();
$posts = $users->posts()->get();
Heres my user Model
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $primarykey = 'user_id';
protected $table = 'users';
public function posts(){
return $this->hasMany("App\Post");
}
}
Heres my posts Model
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $primarykey = 'id';
protected $table = 'posts';
public function post_validation_rules(){
return [
'post_title' => 'required|min:5|unique:posts',
'post_body' => 'required'
];
}
public function user(){
return $this->belongsTo("App\User");
}
public function categories(){
return $this->belongsToMany('App\Category', 'category_id', 'category_id');
}
}
Categories Post
class Category extends Model
{
protected $primarykey = 'category_id';
protected $table = 'categories';
public function posts(){
return $this->belongsToMany('App\Post', 'post_id', 'id');
}
}
Database
Posts Table
id
user_id
post_title
post_body
createad_date
updated_date
Users Table
user_id
username
email
pass
createad_date
updated_date
You can only call relations on a single object, not on an entire collection. $users is a collection of User objects.
If you want a single user object, use the first() function to get the first User object that matches.
$user = User::where('user_id','=','2')->first();
$posts = $user->posts;
Update:
To get the posts directly in the user object, you need to use the with function:
$user = User::with('posts')->where('user_id','=','2')->first();
Try to declare the field that have the relation between your tables then, for example:
$this->hasMany(App\Post::class, 'user_id', 'user_id');
Laravel is searching for a field id in User table but it does not exist. so with this way you will tell it that the field you look is user_id
Normally, I'm dealing with queries I have a two models and I only need to select one model with a whereHas query, which is a greedy condition as it selects as many matches as possible.
Here are my two models:
class Part extends Eloquent {
protected $table = 'parts';
protected $primaryKey = 'part_id';
public function partFlights() {
return $this->hasMany('PartFlights');
}
}
and
class PartFlight extends Eloquent {
protected $table = 'part_flights_pivot';
protected $primaryKey = 'part_flight_id';
public function part() {
return $this->belongsTo('Spacecraft');
}
}
As you can see, there's a 1:m relationship between Part and PartFlight.
What I want is a non-greedy match to select all Part's where all the PartFlight's have the attribute landed set to true. How can I achieve this?
Instead of trying to find out if all are true I suggest you check if none are false ;)
$parts = Part::whereDoesntHave('partFlights', function($q){
$q->where('landed', false);
})->get();
I have a problem here with my Laravel model, i'm trying to use a Pivot Table that I already have in my database, here's the layout of the tables I am using
clients
jobs
clients-jobs
I believe the Error is in my model, I don't completely understand the eloquent syntax, I have been trying several other methods though. I would like to keep the primary on the clients-jobs table in order to index it easier.
Here's my models:
Client
protected $table = 'clients';
public $timestamps = true;
protected $primaryKey = "id";
public function clientsjobs() {
return $this->belongsTo('ClientsJobs');
}
Job
protected $table = 'jobs';
protected $fillable = array('first_name', 'last_name', 'email');
protected $primaryKey = "id";
public function clientsjobs() {
return $this->belongsToMany('ClientsJobs');
}
ClientsJobs ( Maybe I should delete this model? Am I using it right? )
protected $table = 'clients-jobs';
protected $primaryKey = "id";
public function clients() {
return $this->hasOne('Client', 'id');
}
public function jobs() {
return $this->hasOne('Job', 'id');
}
The Code I am using to try and display all of the records for the clients-jobs table is this here in one of my controllers (thanks sebastien):
$masterArray = array();
ClientsJobs::with('clients', 'jobs')->chunk(200, function($records) use (&$masterArray) { //Chunk Retrieves 200 Records at a time
foreach ($records as $record) {
$masterArray[] = array(
'id' => $record->id, // id
'client_name' => !empty($record->clients) ? $record->clients->fname : "Unknown",
'job_name' => !empty($record->jobs) ? $record->jobs->name : "Unknown",
'wage' => $record->wage,
'productivity'=> $record->productivity,
);
}
});
return $masterArray;
this code works for the first two records, but "unknown" after that, I'm pretty sure that it's because the application thinks it's a 1:1 relationship ( I only have 2 Users and 2 Jobs as dummy data ).
Thanks in Advance for any suggestions that you can make, also if you see something nasty that I did please let me know
You should delete the ClientsJobs model, it's unnecessary. Laravel's belongsToMany relationship, when set up correctly will deal with the pivot table itself. Take a look at:
http://laravel.com/docs/4.2/eloquent
Many-to-many relations are a more complicated relationship type. An
example of such a relationship is a user with many roles, where the
roles are also shared by other users. For example, many users may have
the role of "Admin". Three database tables are needed for this
relationship: users, roles, and role_user. The role_user table is
derived from the alphabetical order of the related model names, and
should have user_id and role_id columns.
Your pivot table should either be named with Laravel's convention of taking the model name of each (Singular) and joining them together with an underscore character (client_job) or you can specify the name of the pivot table etc. on your relationship. Laravel's documentation gives the following example which allows you to override the default pivot table name and corresponding keys:
return $this->belongsToMany('Role', 'user_roles', 'user_id', 'foo_id');
In your case, if you're after a one to one relationship, you don't really need a pivot table. You can just implement hasMany and belongsTo relationships. That is, a client belongs to a job, but a job can have many clients.