I am trying to make a relationship with lecturers table and users table. So this is the code of create_lecturers_table
public function up()
{
Schema::create('lecturers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('class03');
$table->integer('class03_stream');
$table->date('class03_from');
$table->date('class03_to');
$table->string('remarks')->nullable();
$table->integer('created_user_id')->unsigned()->nullable();
$table->integer('updated_user_id')->unsigned()->nullable();
$table->foreign('created_user_id')->references('id')->on('users');
$table->foreign('updated_user_id')->references('id')->on('users');
$table->timestamps();
});
}
This is the Lecturer model
class Lecturer extends Model
{
protected $table = 'lecturers';
protected $fillable = [
'class03', 'class03_stream' ,'class03_from','class03_to','remarks','created_user_id','updated_user_id',
];
public function user(){
return $this->hasMany('PMS\User');
}
}
This is the lecturer index function of the controller
public function index(Lecturer $model)
{
return view('lecturers.index',['lecturers' => $model->paginate(15)]);
}
This is the create_users_table
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('user');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('usertype');
$table->boolean('activestatus')->default(false);
$table->rememberToken();
$table->timestamps();
});
}
This is the User model
class User extends Authenticatable
{
use Notifiable;
public function lecturer(){
return $this->belongsTo('PMS\Lecturer');
}
protected $fillable = [
'name', 'email', 'password','usertype',
];
With this what I wants to do is to view the User's name who will create the lecturer via System.So that I have echo the user's name as below in the view.blade.php
<td>{{ $lecturer->user->name }}
When I go to the view it generate this error.
ErrorException (E_ERROR)
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.lecturer_id' in 'where clause' (SQL: select * from `users` where `users`.`lecturer_id` = 1 and `users`.`lecturer_id` is not null) (View: E:\BIT FINAL YEAR PROJECTS\20190419-using-template\resources\views\lecturers\index.blade.php)
Could someone please tell me what is the wrong .
Thanks
I think you have your Eloquent relationships the wrong way around. Try changing them to as follows:
Lecturer
public function user(){
return $this->belongsTo('PMS\User', 'created_user_id');
}
User
public function lecturers(){
return $this->hasMany('PMS\Lecturer', 'created_user_id');
}
Related
I use Laravel 8. I have 3 table. Course table, UserCourse, and User table. I want to get user courses. I tried it with tinker: Course::find(1)->user_courses -it works fine and give back me user_course.
UserCourse::find(1)->user_course - the problem is here, this will return me "null"
How can I get the User Courses?
Course table
Schema::create('courses', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->timestamps();
});
UserCourse table
Schema::create('user_courses', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->foreignId('course_id')->constrained()->onDelete('cascade');
$table->timestamps();
});
User table
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('email')->unique();
$table->string('username')->unique();
$table->string('password');
$table->timestamp('updated_at')->nullable();
$table->timestamp('created_at')->nullable();
});
Course.php
class Course extends Model
{
use HasFactory;
protected $fillable = [
'title',
];
public function user_courses()
{
return $this->hasMany(UserCourse::class);
}
}
UserCourse.php
class UserCourse extends Model
{
use HasFactory;
protected $fillable = [];
public function user_course()
{
return $this->belongsTo(Course::class);
}
}
Your database structure make it that the relation between course and user is a many to many relation with a pivot table in the middle.
Some correction you need to do for it to work seemingly with laravel conventions.
- The pivot table name should be course_user without a primary key
Schema::create('course_user', function (Blueprint $table) {
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->foreignId('course_id')->constrained()->onDelete('cascade');
$table->timestamps();
});
- Remove the UserCourse.php model since it's a pivot
- Define the relation courses in User model as follow
User.php
public function courses()
{
return $this->belongsToMany(Course::class);
}
- Define the relation users in Course model as follow
Course.php
public function users()
{
return $this->belongsToMany(User::class);
}
Now to get any user courses, just run User::find(1)->courses
Same thing to get the users that belongs to the same couses Course::find(1)->users
get courses that the user has not taken:
$userId = 1;
$courses = Course::whereDoesntHave('users', function($userQB) use($userId) {
$userQB->where('id',$userId);
})->get();
I have a project in which I have 3 tables a questions table an answers table and a users table
In the Questions table I have the following:
Schema::create('questions', function (Blueprint $table) {
$table->id();
$table->string('question');
$table->timestamps();
});
In the Users table I have the following:
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('district')->nullable();
$table->string('area')->nullable();
$table->string('committee')->nullable();
$table->string('position')->nullable();
$table->rememberToken();
$table->timestamps();
});
In the Answers table I have the following:
Schema::create('answers', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->unsignedBigInteger('question_id');
$table->foreign('question_id')->references('id')->on('questions');
$table->string('answer');
$table->timestamps();
});
And those are the models
class Answer extends Model
{
public function user(){
return $this->hasOne('App\User');
}
public function question(){
return $this->hasOne('App\Question');
}
}
class Question extends Model
{
public function answer(){
return $this->hasMany('App\Answer');
}
}
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password','district','area','committee','position',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function answer(){
return $this->hasMany('App\Answer');
}
}
Based on my structure the answers table will have entries with each row made of the user_id and his answer to one question and in the following row the other question
How can I retrieve the data in a table where it shows me in the first row the user in a column with all 4 of his answers in the following 4 columns?
First Answer model should be like this. As it's one-to-many.
class Answer extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
public function question(){
return $this->belongsTo('App\Question');
}
}
And then you can get data like this:
$results = User::with('answer')->first();
// this should give the first `user` with all the answers that belongs to the user.
$results = User::with('answer')->get();
// this should give you all the users.
let's say you need all users and all the answers.
foreach ($results as $user) {
echo $user->name;
foreach ($user->answer as $value) {
echo $value->answer;
}
}
Let me know if it helps.
I am getting this error in saving a many-to many relation in laravel eloquent.
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'dream.category_course' doesn't exist (SQL: insert into category_course (category_id, course_id, created_at, updated_at) values (5, 6, 2020-07-05 07:48:06, 2020-07-05 07:48:06))
but the table 'category_course' exists in the database dream..
Here is my category model...
class Category extends Model
{
protected $table = 'categories';
protected $guarded = [];
public function Course()
{
return $this->belongsToMany(Course::class)->using(Category_Course::class)->withTimestamps();
}
and this my course model
class Course extends Model
{
protected $table = 'courses';
protected $guarded = [];
public function user()
{
return $this->belongsTo(User::class);
}
public function category()
{
return $this->belongsToMany(Category::class)->using(Category_Course::class)->withTimestamps();
}
public function course_content()
{
return $this->hasMany(Course_Content::class);
}
and the customize pivot table
class CreateCategoryCourseTable extends Migration
{
public function up()
{
Schema::create('category__course', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('category_id');
$table->unsignedBigInteger('course_id');
$table->timestamps();
});
}
and here is the controller
public function store(Request $request)
{
$data = $request->validate([
'category_id' => 'required',
'title' => 'required|max:20|min:10',
'description' => 'required|min:30|max:100',
'fee' => 'required|integer|min:1500',
'duration' => 'required|integer|between:1,12'
]);
$category_id = $data['category_id'];
unset($data['category_id']);
$user_id = auth()->user()->id;
$course = \App\user::find($user_id)->course()->create($data);
$course->category()->attach($category_id);
return back();
}
I tried everything.I got but still getting this error....
Anyone have any idea..... please
Two underscores in table name
Schema::create('category__course', function (Blueprint $table)
I have this migration table for OFFERS:
public function up()
{
Schema::create('offers', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('article_id')->unsigned();
$table->integer('price');
$table->string('comment');
$table->timestamps();
$table->string('key');
$table->string('title');
$table->timestamp('start');
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->foreign('article_id')
->references('id')
->on('articles')
->onDelete('cascade');
});
}
Also this at model I have:
class Offer extends Model
{
//
protected $fillable = [
'price',
'comment',
'article_id',
'key',
'start'
];
protected $dates = [
'start'
];
public function setStartAttribute($date){
$this->attributes['start']= Carbon::createFromFormat('m/d/Y h:i a', $date);
}
public function getStartAttribute($date){
return (new Carbon($date))->toRfc2822String();
}
public function user(){
return $this->belongsTo('App\User');
}
public function article(){
return $this->belongsTo('App\Article');
}
}
Now at controller I have just store function:
public function store(Requests\OfferRequest $request)
{
$offer = new Offer($request->all());
Auth::user()->offer()->save($offer);
Alert::success('Offer is succesfully added!', 'Good job!')->persistent("Close");
return Redirect::back();
}
Now I also have the same model MAXOFFER. The same is migartion and model.
What I want to do is to add at OffersController store method a query that will chech does start excist in maxoffers table and if not then to add new row with data from request, but if excist row with same start value then to check price and if price is higher than current to update that row...
Please help me to rite that query inside store function at offercontroller...
The following query is created by guessing you have a relation maxoffer in Maxoffer model.
$maxoffer = Auth::user()->maxoffer()
->where('address_id', $request->input('address_id'))
->where('start', $request->input('start'))->first();
if($maxoffer==null)
{
Ath::user()->maxoffer()->create($request->all());
}
else
{
if($maxoffer->price < $request->input('price'))
{
$newOffer = Auth::user()->maxoffer()
->where('address_id', $request->input('address_id'))
->where('start', $request->input('start'))
->update(['price'=>$request->input('price')]);
}
}
Given Eloquent Many To Many relationship:
Migration:
class Topics extends Migration
{
public function up()
{
Schema::create('topics', function(Blueprint $table) {
$table->increments('id');
$table->string('name');
});
Schema::create('topic_user', function(Blueprint $table) {
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->integer('topic_id')->unsigned();
$table->foreign('topic_id')->references('id')->on('topics');
});
}
}
Model:
class User extends Model
{
public function topics()
{
return $this->belongsToMany('App\Topic', 'topic_user');
}
}
I'm wondering how can I delete all topics by given user, currently my code looks like this:
Auth::user()->topics()->delete();
But I'm getting exception:
ERROR: missing FROM-clause entry for table "topic_user" LINE 1: delete
from "topics" where "topic_user"."user_id" = $1 ^ (SQL: delete from
"topics" where "topic_user"."user_id" = 6)
What I'm doing wrong?
That's pretty simple:
Auth::user()->topics()->detach();