combine three tables with keyword with in laravel - php

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

Related

Getting wrong data from database even if I am fetching something different in laravel api

Hello guys I am working on a laravel project for making api for passing the database value in json format but the problem is I have a users table in this table 2 ids 1 is primary key and second is business _id I want to get data according to business_id but it's getting data by id please help me how to solve this issue.
Here is my model code
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class user extends Model
{
protected $table = 'business';
}
Here is my Controller Code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\user;
class GetController extends Controller
{
public function databybusinessid($business _id){
$users = new user();
$users = user::find($business _id);
return response()->json($users);
}
}
Thank you so much
You are using user::find($business _id)
find() method will automatically search by the primary key but none is defined in your model and Eloquent can't decide which one to pick from your table. Therefore, you should explicitly set your primary key in your model by adding the following line.
class user extends Model
{
protected $table = 'business';
protected $primaryKey = 'business_id';
}
If in doubt, you can also fetch database record by a specific column using where
$users = user::where('business_id', '=', $business _id)->get()
Laravel documentation about Eloquent ORM
https://laravel.com/docs/5.8/eloquent
find() Retrieve a model by its primary key..
So you have to use your code as:
$users = user::where('business_id',$business_id)->first();
// Notice first() Retrieve the first model matching the query constraints...
Or you can change your primary code in model
namespace App;
use Illuminate\Database\Eloquent\Model;
class user extends Model
{
protected $table = 'business';
protected $primaryKey = 'business_id';
}
find() works only on primary key. you need to use where instead.
or you can define business_id as primary key in your User model.
protected $primaryKey = 'business_id';
public function databybusinessid($business _id){
$users = new user();
$users = user::where('business_id',$business _id)->first();
return response()->json($users);
}

Eloquent model relationship

Project model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
protected $table = 'project';
protected $primaryKey = 'project_id';
}
Developer model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Developer extends Model
{
protected $table = 'developer';
protected $primaryKey = 'id';
}
I want to join this two model as the SQL below :
SELECT developer.developer_name, count(project.dev_id)
FROM project
JOIN developer ON developer.id = project.dev_id
GROUP BY developer.developer_name
Can someone help me? I am confused when looked through different documentation.
Please guide me the correct way.
Create a projects relation in Developer model.
public function projects()
{
return $this->hasMany(\App\Project::class, 'dev_id')
}
Then you can get all developers with number of projects they are handling using
Developer::withCount('projects')->get();
You can do this using below query and also you can do this by eloquent query for this you have to define relationship in model.
DB::table('project')
->join('developer', 'project.dev_id', '=', 'developer.id')
->select('developer.developer_name', DB::raw("count(project.dev_id) as count"))
->groupBy('developer.developer_name')
->get();

Retrieving error on one to many relationship laravel

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

Laravel 5.3 Eloquent Model Relationship not working, Returns NULL

I am new to Laravel and am struggling with this:
Database - MSSQL existing DB schema cannot be modified as other software depends on it. (not sure if this is a problem or not)
Model/Table setup:
INFO_ALL Table - ID is primary key
PERSON Table - ID is foriegn key
ID's are hex values and I notice eloquent removes the 0x from the start of the value and am not sure if this is causing the relationship to fail or not. example: in the DB I see 0x123456789 in my returned eloquent data I see 123456789
Person Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Person extends Model
{
protected $table = 'PERSON';
protected $primaryKey = 'ID';
public $incrementing = false;
public $timestamps = false;
public function info_all(){
return $this->belongsTo(Info_All::class, 'ID', 'ID');
}
}
Info Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Info_All extends Model
{
protected $table = 'INFO_ALL';
protected $primaryKey = 'ID';
public $incrementing = false;
public $timestamps = false;
public function person(){
return $this->hasOne(Person::class, 'ID', 'ID');
}
}
How I am testing the relationship:
php artisan tinker
$person = App\Person::first();
$person->info;
NULL
php artisan tinker
$info= App\Info::first();
$info->person;
NULL
I know this relationship exists in the DB and I can manuualy get them together with a query but the relationship feature of this framework would really be nice to get figured out.
Beign new to Laravel there are a few things I am unsure about, like if the third argument in the realationship is neccesary since I am declaring the $primaryKey. I declared the $primarykey in the first model because I assummed it is case sensative and my table has ID not id. That being said, I have been stuck on this for a couple days and feel like I have tested everything in every different combination.
Any help is appreciated.
Your relation is defined incorrectly. Try by adding following relation:
Person Model
public function info()
{
return $this->hasOne(Info_All::class, 'ID', 'ID');
}
Info_All model
public function person()
{
return $this->belongsTo(Person::class, 'ID', 'ID');
}
Then try it out in tinker:
$person = App\Person::first();
$person->info;
I am not sure but if eloquent removes the 0x from the start of the value then it can also cause the problem.
Try by removing 0x from your tables.

How to delete record 1 and record 2 in different table using relationship in laravel 5.1

Here we go in my situation I have videos and video_tags table and it has a relationship one to many because in a video has many tags. I'm trying to achieve to delete record1 and record2 storing in different table using relationship in one query only then the records will be deleted from table1 and table2. I think it is possible in laravel please i need help.
Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Video extends Model
{
protected $table = 'videos';
protected $guarded = ['id'];
public function tags()
{
return $this->hasMany('App\VideoTag');
}
}
Controller:
public function postDeleteVideo(Request $request, $id){
$tag = Video::find($id)->tags->delete();// <-- problem here
return response()->json(array('success'=>true));
}
What you need is to set CASCADE relationships in your database.
Then...
$video = \Video::find(1);
$video->delete();

Categories