retrieve name from the other table - database

Is there an efficient way of retrieving the name by using select and join clause? I have a Note, NoteType and NoteStatus model. There are type and status field which will be stored as integer (representing the id of its respective model) inside Note model. NoteType and NoteStatus models have id and name fields.
foreach($notes as $note)
{
$type=NoteType::where('id',$note->type)->first();
$note->type=$type->name;
$status=NoteStatus::where('id',$note->status)->first();
$note->status=$status->name;
}

Model Relations
Setting up relations between your models would be the best way as you then don't need to re-invent the wheel each time you need to call the join. It will save you code in the long run.
More info on this here:
Laravel Eloquent Relationships
Query Builder
If you want to do this manually then it would be the same as if you ran the query in raw SQL:
$note = Note::join('NoteType','Note.NoteType_id','NoteType.id')
->select('Note.*','NoteType.Name as NoteName')
->first();
Now you can get all the info from $note
Note id = $note->id
NoteType Name = $note->NoteName
Obviously adjust this to your code but this should help you build your knowledge enough to work it out.
More info can be found here:
Laravel Query Builder Joins

Assume that Your model name is Note.php
assume in your notes table has note_status_id and note_type_id foreign key
Add Relationship in your main model Note.php
public function status()
{
return $this->belongsTo(NoteStatus::class);
}
public function notes()
{
return $this->belongsTo(NoteType::class);
}
You can retrieve data with relationship something like that
Note::with('status','notes')
->get()
For more info regarding laravel relationship Laravel Eloquent: Relationships

Related

How to retrieve a model and it's relationship as a single Array or Object | Eloquent, Eloquent: Relationships

i have 3 tables with one-to-one relationship. The phone table has one to one relationship with Model table and Model table has a one to one relationship with Manufacturer table.
phone_table
id
imei
image
model_id
model_table
id
name
image
manufracturer_id
manufracturer_table
id
name
logo
how to get a result like this :-
App\Phone{
imei : "356554512522148",
model : "Galaxy S-10",
manufracturer : "Samsung",
}
I would never throw it into the same array / object, i would firstly do that on transformation. If you use default Laravel transformation you can use getters for it. Simple example on how to access these fields into the same context would be.
$phone = Phone::with('model.manufactor')->find(1);
With secures the queries are optimal for accessing it. How to get data into same layer.
[
'imei' => $phone->imei,
'model' => $phone->model->name,
'manufactor' => $phone->model->manufactor->name,
]
For this to work, you need relations in your model too.
Phone.php
public function model()
{
return $this->belongsTo(Model::class);
}
Model.php
public function manufactor()
{
return $this->belongsTo(Manufactor::class);
}
Just join them:
\App\Phone::leftjoin('model_table AS mo', 'mo.id', '=','phone_table.model_id')
->leftjoin('manufracturer_table AS ma', 'ma.id', '='. 'mo.manufracturer_id')
->selectRaw('phone_table.imei, mo.name AS model, ma.name AS manufracturer')
->first()
And sometimes you need to think about why you want to split table to one-to-one relationship.
Is there a table not usually be used, or one of them need to be connected by another tables. is this just for saving space or reduce IO cost.
If there are not any other reason and you always need to get these tables' information, maybe you can merge to one table.

How do I query a polymorphic pivot table with Eloquent & Laravel 5

I have 3 tables. 1 that defines videos, 1 that defines carousels and 1 pivot table that defines which carousel a video belongs to if it even belongs to any.
I have tried to describe my tables below in as simple a way as possible
Videos Table
id title user
Feature Table (Pivot)
id carousel_id video_id
Carousel Table
id carousel_type
How can I query the database for all videos in the Feature table with a given carousel type using Eloquent models relations. I am using Laravel 5 if that makes a difference. I have tried the morphMany as described in their documentation but I must be doing something wrong.
Thanks!
Edit:
Table names:
videos,
features,
carousels
Model names:
Video,
Feature,
Carousel
#
Edit 2:
Tables:
casts,features,featureables
Models:Cast, Feature
Here are the files that I am currently having trouble with.
Controller:
class castController extends Controller {
public function index()
{
$carousel_casts = \App\Feature::find(1)->casts;
foreach($carousel_casts as $casts){
echo $casts->title . "<br>";
}
}
}
Model:
public function casts()
{
return $this->belongsToMany('\App\Cast','featureables');
}
I have specific table names for a reason, I am taking over a pre existing project and the table names can't change. The current tables are casts(video), features(the carousel table), featureables(the pivot table).
I can query all of these tables seperatly without issue, however when I use the belongsToMany relationship I get the following error.
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'featureables.feature_id' in 'field list' (SQL: select casts.*, featureables.feature_id as pivot_feature_id, featureables.cast_id as pivot_cast_id from casts inner join featureables on casts.id = featureables.cast_id where featureables.feature_id = 1)
First, rename features table to carousel_video.
Next, define relationship in your Carousel model like:
public function videos()
{
return $this->belongsToMany('YourAppNamespace\Video');
}
Then, query the Carousel model like:
$videos = Carousel::find(2)->videos; //finds all videos associated with carousel having id of 2
return $videos;
You can do the opposite by defining a relationship on your Video model like:
public function carousels()
{
return $this->belongsToMany('YourAppNamespace\Carousel');
}
And, querying like:
$carousels = Video::find(2)->carousels; //finds all carousels associated with video having id of 2
return $carousels;

Laravel get value of column from relation through pivot on load() after all()

I have a problem retrieving values of a column from relations in Laravel.
I have a User - Model. This model has relation to a table btw. a model named Userhobbies.
For now we have:
User ::: hasMany >>> Userhobbies
Now with User::all()->load('hobbies') I'm getting right results like
{"id":"1","username":"jdoe","first_name":"Joe","last_name":"Doe","birth":"
1992-04-11","picture_id":"f3dca65323e876026b409b9ba3d49c56","hobbies":
[{"hobby_id":"1","user_id":"1"},{"hobby_id":"2","user_id":"1"},
{"hobby_id":"3","user_id":"1"},{"hobby_id":"4","user_id":"1"}]}
As you can see Userhobbies contains only primary-key relations between hobby - table (Hobby Model) and user - table (User Model).
(Hobby model also has hasMany relation to Userhobbies)
My question now is - how to retrieve all hobby-names (from hobby - table) in my call over (after load('hobbies') ) and is it possible without writting a lot of code?
For better understanding of my idea the result which I want to retrieve:
{"id":"1","username":"jdoe","first_name":"Joe","last_name":"Doe","birth":"
1992-04-11","picture_id":"f3dca65323e876026b409b9ba3d49c56","hobbies":
["golf", "cards", "games", "football"]}
EDIT:
If I try following (I tried with belongsToMany in User and Hobby):
User::with('hobbies')->get()->first()
And I'm getting the whole values from the hobbies - table:
{user-specific data ...
hobbies:[{"id":"1","name":"golf","created_at":"2015-04-07
14:15:02","updated_at":"2015-04-07 14:15:02","pivot":
{"user_id":"1","hobby_id":"1"}},
{"id":"2","name":"cards","created_at":"2015-04-07
14:15:02","updated_at":"2015-04-07 14:15:02","pivot":
{"user_id":"1","hobby_id":"2"}},
{"id":"3","name":"games","created_at":"2015-04-07
14:15:02","updated_at":"2015-04-07 14:15:02","pivot":
{"user_id":"1","hobby_id":"3"}},
{"id":"4","name":"football","created_at":"2015-04-07
14:15:02","updated_at":"2015-04-07 14:15:02","pivot":
{"user_id":"1","hobby_id":"4"}}]}
Same try with ->load('hobbies'). I really don't know how to go on.
To explain it a bit more what I need one could imagine such query as follows:
User::all(['id', 'name'])->load(array('hobbies.id','hobbies.name'))->get();
From my knowledge, I know that it's possible to use a closure to set constraints on the query that performs the load, like so:
User::all()->load(['hobbies' => function($query)
{
$query->select('id', 'name');
}]);
By doing it, when you cast it to array, it will produce a result near to what you want. You can even add 'pivot' to your $hidden property on your Hobby model to hide this information.

Eloquent How to Omit Row if value is empty

I have three tables.
Customer
Product
Reviews
I have used Eloquent for mapping these tables.
For example,
In Review Model for customer details I have function like
public function customer(){
return $this->belongsTo('Customer', 'customer_id');
}
and for product details I have function like
public function product(){
return $this->belongsTo('Product', 'product_id');
}
Now Querying reviews model like
Review::all()->with(array('customer', 'product'))->get()
returns the values. That is fine. But, if any customer is deleted, then the value for the row is just empty. Instead I need to omit that row. How to do this in laravel.
Try this... Perhaps adding the where clause to your approach works too.
$allReviews = Review::all()
->join('customers', 'reviews.customer_id', '=', 'customers.id')
->join('products', 'reviews.product_id', '=', 'products.id')
->where('customers.firstname','!=','') // given that there is a column firstname in table customers
->get()
You can use has() to filter for models that have at least one related model:
Review::with('customer', 'product')->has('customer')->get();

Retrieving data from referenced key table - Laravel-4

The structure of concerning tables is as follows (MySQL):
//Table Name : team
tid PK
team_name (varchar)
//Table Name : fixture
fid PK
home_team_id FK |_ both referenced to 'tid' from 'team' table
away_team_id FK |
My aim is to retrieve the team names. Considering this structure, I think I'll have to retrieve home_team_id and away_team_id and then do something like
Fixture::where('tid','=',$home_team_id)->get();
My question is, is this the correct way to accomplish what I aim to do?
and
should this be done from the controller? (if so, then I'll have to do two queries from same function)
First, rather than having your primary keys be tid and fid, just keep them both as id. This is not only best practice, but will allow you to more easily use Laravel's Eloquent ORM as it by default assumes your primary key column is named id.
Second thing, make sure your table names are in plural form. Although this is not necessary, the example I'm about to give is using Laravel defaults, and Laravel assumes they are in plural form.
Anyway, once you've 'Laravelized' your database, you can use an Eloquent model to setup awesome relationships with very minimal work. Here's what I think you'd want to do.
app/models/Team.php
class Team extends Eloquent {
// Yes, this can be empty. It just needs to be declared.
}
app/models/Fixture.php
class Fixture extends Eloquent {
public function homeTeam()
{
return $this->belongsTo('Team', 'home_team_id');
}
public function awayTeam()
{
return $this->belongsTo('Team', 'away_team_id');
}
}
Above, we created a simple model Team which Laravel will automatically look for in the teams database table.
Second, we created model Fixture which again, Laravel will use the fixtures table for. In this model, we specified two relationships. The belongsTo relationship takes two parameters, what model it is related to, in both cases here they are teams, and what the column name is.
Laravel will automatically take the value in away_team_id and search it against the id column in your teams table.
With just this minimal amount of code, you can then do things like this.
$fixture = Fixture::find(1); // Retrieves the fixture with and id of 1.
$awayTeam = $fixture->awayTeam()->first(); // var_dump this to see what you get.
$homeTeam = $fixutre->homeTeam()->first();
Then you can proceed as normal and access the column names for the tables. So say you have a 'name' column in the teams table. You can echo out the the home team name from the fixture like so.
$fixture = Fixture::find(1); // Get the fixture.
echo $fixture->homeTeam->name;
It's nearly 2AM, so there might be an error or two above, but it should work.
Make sure you check the docs for Eloquent, especially the bits relating to relationships. Remember to name your columns and tables in the way Laravel wants you to. If you don't, there are ways to specify your custom names.
If you want to get even more fancy, you can define the inverse relationship like this on your Team model.
app/models/Team.php
class Team extends Eloquent {
public function fixturesAtHome()
{
return $this->hasMany('Fixture', 'home_team_id');
}
public function fixturesAway()
{
return $this->hasMany('Fixture', 'away_team_id');
}
}
Then to get all of a particular team's home fixtures...
$team = Team::find(1); // Retreive team with id of 1;
$homeFixtures = $team->fixturesAtHome();

Resources