How to convert sql query to eloquent in laravel - laravel

how to convert sql to eoquent
$getAllRequirementRecord = Requirement::select()
->join('requirement_locations','requirements.id','=','requirement_locations.requirement_id')
->join('locations','requirement_locations.location_id','=','locations.id')
->where('isdelete',2)
->where('requirements.id',$id)->get();
help to solve this problems

Let's say we've an eloquent Model named Requirement and we've a database table named requirements associated with that model and we have another model named requirementLocation associated with a database table named requirement_locations.
and we have a database relation ship between both tables "requirements" & "requirement_locations" based on the requirement_id
Requirement Model:
class Requirement extends Model{
protected $table = 'requirements';
}
RequirementLocation Model:
class RequirementLocation extends Model{
protected $table = 'requirement_locations';
}
and Now we need to setup a relationship between these two models like the database tables .. so inside the Requirement we're gonna use has many relationship
use App\RequirementLocation;
class Requirement extends Model{
protected $table = 'requirements';
public function locations(){
return $this->hasMany(RequirementLocation::class);
}
}
and simply to fetch your data use
$id = 1;
$getAllRequirementRecord = Requirement->whereHas('locations' , function($query){
$query->where('isdelete',2);
})->where('id',$id)->with('locations')->get();

You can use eloquent with SQL raw query likewise:
$activeusers = User::selectRaw('users.name, count(*) submitted_games')
->join('games', 'games.user_id', '=', 'users.id')
->groupBy('users.name')
->orderBy('submitted_games', 'DESC')
->get();
To output to the screen the last queries ran you can use this :
dd(DB::getQueryLog());

I hope you have created Requirement, Location and RequirementLocation models
So first add this code in Requirement.php model file:
public function locations()
{
return $this->hasMany('RequirementLocation', 'requirement_locations');
}
Then access the requirements like this :
$requirement = Requirement::where('id', $requirement_id)->first();
Now you can access locations like this :
$requirement->locations;

Related

laravel eloquent migrations

In laravel eloquent relationship, is it still necessary to make migration even though there's an existing database? beginners here.
I create a one-to-one eloquent relationship inside my model to get the specific column from another table's record and fetch to the datatable, but it did not work.
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Directorystatus extends Model
{
use HasFactory;
protected $table = 'user_status';
protected $fillable = ['status_id' , 'status_xtitle'];
public function userbasic() {
return $this->belongsTo(directorybasic::class,'user_xusern','status_xuser');
}
}
class Directoryuser extends Model
{
use HasFactory;
protected $table = 'user_basic';
protected $primaryKey = 'user_id';
protected $fillable = ['user_id' , 'user_xusern' , 'user_xfirtname' ,'user_xmiddlename','user_xlastname'];
public function userstatus() {
return $this->hasOne(directorystatus::class,'user_xusern','status_xuser');
}
}
No. Migrations are not necessary. Defining relationships on both sides is also not necessary, if you don't need them both. (You can have only belongsTo, without having hasOne or hasMany in the opposite model.)
First, make sure you are using the right object (Directorystatus::class / Directoryuser:class - I see they're not capitalized in your code). The next param is the foreign key, meaning the column which points to a model's primary key. The third param is optional and is used only if the primary key is not id.
For example if you have a column status_xuser in the table user_status, which contains a user_id from user_basic table, you should define it like this:
public function userbasic() {
return $this->belongsTo(Directoryuser::class,'status_xuser','user_id');
}
And in order to use this relationship, when you retrieve a model from the db, for example, you should call on it the same way your relationship function is named.
$status = Directorystatus::find(1);
$user = $status->userbasic();
I would also suggest you name your classes in camelCase, because it's the accepted practice (in Laravel especially).

Laravel relation one to many get results joined

I'm kinda lost one this one, I really can't find the problem, I have been watching a lot of questions all over the web but still can't seem to put this working properly.
I have two tables, the tabelaAngaricao table and the tabelaFotos table with a relationship of one-to-many, meaning that a tabelaAngariacao can have many tabelaFotos, and tabelaFotos as a angariacaoid(foreign key) so my tabelaAngariacao model is:
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\TabelaFotos;
class TabelaAngariacao extends Model
{
protected $table = 'tabelaAngariacao';
public function TabelaFotos()
{
return $this->hasMany(TabelaFotos::class, 'angariacaoid');
}
}
and my tabelaFotos model is:
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\TabelaAngariacao;
class TabelaFotos extends Model
{
protected $table = 'tabelaFotos';
public function TabelaAngariacao()
{
return $this->belongsTo('App\TabelaAngariacao');
}
}
What I want is to get all results joined by the angariacaoid, so in my controller I have:
public function index()
{
$results = DB::table('tabelaAngariacao')
->leftJoin('tabelaFotos', 'tabelaAngariacao.id', '=', 'tabelaFotos.angariacaoid')
->select('tabelaAngariacao.*')
->get();
}
Could someone help me on finding the problem? What is that I'm doing wrong?
You don't need to add select. Try following
$results = DB::table('tabelaAngariacao')
->leftJoin('tabelaFotos', 'tabelaAngariacao.id', '=', 'tabelaFotos.angariacaoid')
->get();
The above script will give you columns from both tables.
And probably you don't need to use DB::table, you can use Eloquent Queries instead, since you've defined your relationsips
You can try it by doing this.
$results = TabelaFotos::with('TabelaAngariacao')->get();
Here is how it works
$results = ModelName::with('relationship_in_model_name')->get();
Hope it works

laravel use field in Eloquent model from another table

I have a model named "User". I want "Password" field from Eloquent from another table, and when user calls the user::all() method, all selected fields from different tables come in the result.
How can i do that?
Results are not displayed in with() .
my problem solved by using $appends in Eloquent model .
my code :
class User extends Eloquent {
protected $table = 'user';
protected $attributes = ['password'];
protected $appends = ['password'];
public function getPasswordAttribute()
{
return $this->getPAsswordMethod();
}
}
Your question is extremely board and borderline unanswerable but I will give you a board solution.
You are able to establish relationships to other tables via the Model objects you create. Lets pretend you have a Password table which belongs to the User.
User model:
public function password()
{
return $this->hasOne(Password::class, 'FK', 'PK');
}
You can now do User::with('password')->get(['FieldName']); and this will give you all of the passwords which have the above relationship to a user.

Issue with Laravel hasMany relation

I’m having an issue with relations in two of my models in a Laravel application. My models are:
class Invoice extends Eloquent {
protected $table = 'invoices';
public function line_items()
{
return $this->hasMany('LineItem');
}
}
And:
class LineItem extends Eloquent {
protected $table = 'line_items';
public function invoice()
{
return $this->belongsTo('Invoice');
}
}
In my controller, I fetch an Invoice row with the following:
$invoice = Invoice::find($id);
However, if I try and access the line_items property to fetch the LineItem rows relating to my invoice, I get the following error:
Invalid argument supplied for foreach()
Why is this? I’ve set my models up as per Laravel’s documentation: http://laravel.com/docs/eloquent#one-to-many
change
public function line_items()
for
public function lineItems()
and it will work , tested in Laravel 4.1 :)
Check your tables relations... (Schema)
Your FK must be lineitem_id... You have modified this? Laravel will configure automatically... Don't change this...
Then, try
$invoice->line_items() or $invoice->line_items in 4.1
Check for line_items before the foreach loop:
if(! $invoice->line_items->isEmpty()){
foreach($invoice->line_items as $line_item){
//do stuff
}
}
Also, it won't hurt to explicitly mention the FK, although laravel will automatically try to do it for you provided you use proper names for your table fields.
//Invoice Model
return $this->hasMany('LineItem', 'invoice_id');
//LineItem Model
return $this->belongsTo('Invoice', 'invoice_id');

Laravel 4 - How to use where conditions for relation's column

This is what I want, I have two tables. one is 'Restaurants' and other is 'Facilities'.
The tables are simple.. and One-To-One relations. like there is a restaurant table with id, name, slug, etc and another table called facilities with id, restaurant_id, wifi, parking, etc
Here are my models:
class Restaurant extends Eloquent {
protected $table = 'restaurants';
public function facilities() {
return $this->hasOne('Facilities');
}
}
class Facilities extends Eloquent {
protected $table = 'facilities';
public function restaurant() {
return $this->belongsTo('Restaurant');
}
}
I want do like this Select * from restaurants r left join facilities rf on r.id=rf.restaurant_id where r.name = 'bbq' and rf.wifi != '1'.
How to use Eloquent to do that?
ps. sorry for modify from https://stackoverflow.com/questions/14621943/laravel-how-to-use-where-conditions-for-relations-column#= , but I have the similar problem.
You can use where and other sql-based methods on the relationship objects.
That means you can either create a custom method in your model:
class Restaurant extends Eloquent {
protected $table = 'restaurants';
public function facilities($wifi) {
return $this->belongsTo('Facility')->where('wifi', '=', $wifi);
}
}
Or you can try to use query scopes:
class Restaurant extends Eloquent {
protected $table = 'restaurants';
public function facility() {
return $this->belongsTo('Restaurant');
}
public function scopeFiltered($query, $wifi)
{
return $query->where('wifi', '>', 100);
}
}
Then:
$wifi = 1;
$restaurants = Restaurant::facilities()->filtered($wifi)->get();
This isn't exactly what you need likely, but query scopes is likely what you want to use to get what you're attempting.
THe key point is to know that relationship classes can be used like query builders - for example:
$this->belongsTo('Facility')->where('wifi', '=', $wifi)->orderBy('whatever', 'asc')->get();
There are some ways to filter both, this is using QueryBuilder:
Restaurant::join('facilities','facilities.restaurant_id','=','restaurants.id')
->where('name','bbq')
->where('facilities.wifi','!=', 1)
->get();

Resources