i want to create a query with multiple tables
the query that i need is:
SELECT orders.user_id, orderitem.product_id, orderitem.orderItem_quantity, product.product_price, product.product_imgPath,product.product_name
FROM orderitem, orders, product, users
WHERE orders.user_id = '$_Session[user_id]'
AND orderitem.product_id = product.product_id
AND orderitem.order_id = orders.order_id
AND orders.order_status = 1
and i try these codes:
1:
$cartProducts = DB::table('orderitem')
->join('product','product.product_id','=','orderitem.product_id')
->join('orders','orders.order_id','=','orderitem.order_id')
->where('orders.order_status','=','Waiting')
->where('orders.user_id','=',$userId)
->select('orderitem.*','orders.*','product.*','users.*')
->get();
The error that i get is:
SQLSTATE[42S02]: Base table or view not found: 1051 Unknown table 'users'
2:
$cartProducts = DB::table('orderitem','orders','products','users')
->select('orderitem.*','orders.*','products.*','users.*')
->where('orders.user_id','=',$userId)
->where('orderitem.product_id','=','product.product_id')
->where('orderitem.order_id','=','orders_id')
->where('order_status','=','Waiting')
->get();
The error that i get is:
SQLSTATE[42S02]: Base table or view not found: 1051 Unknown table 'orders'
And i know that i can't use multiple parameter for table function
Use laravel relationships https://laravel.com/docs/5.5/eloquent-relationships#one-to-many
First, in your User model do:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function images()
{
return $this->hasMany('App\Images'); //make sure your images table has user_id column
}
}
And then in your Image table model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
Now in your controller:
$data = App\Post::user(1)->with('images');
return view('view_name', ["data" => $data]);
Your view:
#foreach($data->images as $image)
<img src="{{ $image->url }}">
#endforeach
Related
Here is my database table.
to_user_id is deleted in the users table that time total_like not should be 1
Here is my code
$user_id = 585;
$list = new self;
$list = $list->where('users.id', $user_id);
$list = $list->leftJoin('user_like_dislikes as total_like', function ($join) use ($user) {
$join->on('users.id', '=', 'total_like.to_user_id')
->where('total_like.like', 1);
});
$list = $list->select('users.*', \DB::raw('count(total_like.like) as total_like')
$list = $list->first();
Here are my user_like_dislikes data table
user_id
to_user_id
like
585
590
1
Here is my user table
id
deleted_at
590
Null
I above code to_user_id is not deleted in the user table so the output is total like is 1
But when I delete to_user_id in the users table that time output is total like 1 getting. this is wrong.
So, I want where I delete to_user_id in the users table that time total like should be 0
better way use relation to get solve this problem.
try bellow code :
in user model :
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
class User extends Model
{
protected $table = 'users';
public function likes(): HasMany
{
return $this->hasMany(Like::class, 'to_user_id', 'id');
}
}
the Like model:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Like extends Model
{
protected $table = 'user_like_dislikes';
public function user(): BelongsTo
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
}
And Finally your query is:
$data = \App\Models\User::query()
->where('id',585)
->withCount('likes as likes_count') // for getting count of rows
->withSum('likes as likes_sum','like') // for getting sum of like column
->first();
$data->likes_count and $data->likes_sum your want value
and for handle soft delete you should use bellow tarit in user model
use \Illuminate\Database\Eloquent\SoftDeletes;
I have 3 tables
students
- id
- name
classes
- id
- name
student_class
- id
- student_id
- class_id
- score
I want to return a list of the students that belong to class_id = 100
$students = \Student::where(['class_id' => 100])->get();
this is my Student Class
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
protected $table = 'students';
public function store(Request $request)
{
$student = new Student;
$student->save();
}
}
the error I´m getting is:
<strong>Message:</strong> SQLSTATE[42S22]: Column not found: 1054 Unknown column 'class_id' in 'where clause' (SQL: select * from `students` where (`class_id` = 100))
update: I can do
$students = \Class::find(100)->with(['students'])->get();
and it will return all the students as a child of classes but I don´t need that.
I need the data from students and the pivot table (student_class) in particular de score column.
thank you for your help
Update your student model as
public function classes(){
return $this->belongsToMany(Class::class, 'student_class', 'student_id', 'class_id');
}
//query
Student::whereHas('classes', function ($query) {
$query->where('id', 100);
})->get();
UPDATE : in both of your model relation add
return $this->belongsToMany('App\Class')->withPivot('score');
now you can do this inside your loop
foreach ($student->classes as $class) {
echo $class->pivot->score;
}
Laravel picks the wrong table, the users table. I have switched the table in config/auth to the correct one but for some reason, Laravel still uses the default users table.
Code
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class UserLoginController extends Controller
{
protected $table = 'pupil';
public function showLoginForm()
{
return view('home');
}
public function login(Request $request)
{
$this->validate($request, [
'user' => 'required',
'password' => 'required|min:3'
]);
$user = User::where('accountName', $request->user)
->where('password', $request->password)
->first();
if ($user) {
Auth::login($user);
return redirect()->route('neue_anmeldung');
}
return redirect()->back()->withInput('email');
}
}
I get the following error message.
SQLSTATE[42S02]: Base table or view not found: 1146 Table
'database1.users' doesn't exist (SQL: select * from users where
accountName = 6001 and password = password limit 1)
Your User model is configured to use the users table. You have defined the table in your controller which is wrong. You need to define the property protected $table = 'pupil'; in your App\User.php
By default eloquent Will assumes the tables as follows
For Example
If Your Model name is
User Then it will search for users table in database
AdminUser Then it will search for admin_users table in database
To Change the default tablename assumed by eloquent
Open Your Current Model
Not Your Controller
and protected $table = 'yourTableNAme';
Hope it helps
The problem is that the query can't find the specific_method(specific_method, specific_model,SpecificModel,specificMethod etc...), that should been joined with the method WITH from Laravel Eloquent. Any ideas how to solve it?
My code:
//SpecificModel
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class SpecificModel extends Model {
protected $guard_name = 'web';
protected $table = 'SpecificTable';
protected $guarded = ['id'];
public function specificMethod(){
return $this->belongsTo('App\Models\AnotherModel','AnotherModel_id');
}
}
//AnotherModel
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class AnotherModel extends Model {
protected $guard_name = 'web';
protected $table = 'AnotherTable';
protected $guarded = ['id'];
}
//Query method
$model = app('App\Models\SpecificModel');
$query = $model::with('specificMethod:id,title');
$query = $query->orderBy('specific_method.title','desc');
return $query->get();
//Error
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column
'"specific_method.title"' in 'order clause' (SQL: select * from
`SpecificModel` where `SpecificModel`.`deleted_at` is null order by
`specific_method`.`title` desc)
This happens because the belongsTo relationship does not execute a join query as you expect it to (as you can see from the error you get). It executes another query to get the related model(s). As such you will not be able to order the original model by related models columns.
Basically, 2 queries happen:
Fetch the original model with SELECT * from originalModel ...*
Fetch the related models with SELECT * from relatedModel where in id (originalModelForeignKeys)
Then Laravel does some magic and attaches the models from the 2nd query to the correct models from the first query.
You will need to perform an actual join to be able to order the way you want it to.
I want to save an object with Laravel's eloquent but I get error 500 when trying to save.
This is my model code:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Categorie extends Model
{
}
and this is my action:
public function addCategorie() {
$input = Input::all();
$categorie = new Categorie;
$categorie->libelle = $input['label'];
$categorie->save();
return $categorie;
}
When I use print_r($categorie) after the save method I get a result, but when I use the save() method I got this error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'updated_at' in 'field list' (SQL: insert into `categories` (`libelle`, `description`, `updated_at`, `created_at`) values (sss, zzz, 2015-12-23 16:20:30, 2015-12-23 16:20:30 ))
In your migration file for categories table, you need to have
Schema::create("categories", function($table){
// Id, name, etc
$table->timestamps();
}
so that eloquent queries can update when this entry was created and saved, or created_at and updated_at. If you don't want to use these timestamps, add
class Categorie extends Model {
public $timestamps = false;
}
to your Categorie model.