Laravel Many To Many Get Fields From Both Tables - laravel

I have 3 tables:
Genre model: id, name, slug, etc.
GenreStation model: id, genre_id, station_id.
Station model: id, name, slug, logo, etc.
I'm trying to get data by genre slug from station table with offset and limit parameters. But also I want to fetch genre name using this query:
Genre::slug($genreSlug)
->first()
->stations()
->skip($offset)
->take($limit)
->get([
'genres.name as genre_name',
'stations.id',
'stations.name',
'stations.slug',
'stations.stream_url',
'stations.logo',
'stations.media_type',
'stations.bit_rate',
'stations.listeners',
'stations.status',
]);
I'm getting the following error:
"Illuminate\Database\QueryException","message":"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'genres.name' in 'field list' (SQL: select genres.name as genre_name, stations.id, stations.name, stations.slug, stations.stream_url, stations.logo, stations.media_type, stations.bit_rate, stations.listeners, stations.status, genre_station.genre_id as pivot_genre_id, genre_station.station_id as pivot_station_id, genre_station.created_at as pivot_created_at, genre_station.updated_at as pivot_updated_at from stations inner join genre_station on stations.id = genre_station.station_id where genre_station.genre_id = 1 limit 15 offset 0)","file":"/home/vagrant/Projects/MuzzaLife/vendor/laravel/framework/src/Illuminate/Database/Connection.php","line":625
Without genre.name field everything works fine. How can I solve this problem?

In the SQL query you can already see what is going wrong. Probably the first query will get you the Genre, but afterwards a new query is made for the stations and they are based on the genre_station table. You don't have any information from the genres table, so you should add this.
You can do this by adding a join to the query..
http://laravel.com/docs/5.1/queries#joins
Or first save the Genre in a separate variable and get the stations after..
$genre = Genre::slug($genreSlug)->first();
$stations = $genre->stations()
->skip($offset)
->take($limit)
->get([
'stations.id',
'stations.name',
'stations.slug',
'stations.stream_url',
'stations.logo',
'stations.media_type',
'stations.bit_rate',
'stations.listeners',
'stations.status',
]);

Related

Laravel Join Query to get all matching records

i want to get al product attributes (if any) for the given product id using a sub query in join.
Below is my query
$product_attributes = ProductAttributes::select('name as attribute_name', 'value as attribute_value')->get();
$data['product']= Product::select('products.*','vendors.name as vendor_name','product_discounts.start_time',
'product_discounts.end_time', 'product_discounts.discount_type','product_discounts.discount_value','product_attributes.name','product_attributes.value')
->leftjoin('product_discounts','products.id','=','product_discounts.product_id')
->joinSub($product_attributes, 'product_attributes', function ($join) {
$join->on('products.id', '=', 'product_attributes.product_id');
})->leftjoin('vendors','products.vendor_id','=','vendors.id')->where('id',$request->product_id)->first();
This query gives me following error
InvalidArgumentException A subquery must be a query builder instance,
a Closure, or a string.
if i use simple leftjoin with product attributes it gives me on last item from the product_attributes table .
can someone please guide me how can I list all the product attributes against the product without loop . Below is the table for product attributes
use ->get() instead of ->first();

Where not in with a belongs to relationship in laravel

I have two table named 'districts' & 'division' as follows:
division table
districts table
division model hasMany districts
Now I want to get all division with districts except some districts. I am trying as follows:
$divisionWithDistricts = Division::with('districts')->whereNotIn('districts.id',$districtsAlreadyUsed)->get();
Here districtsAlreadyUsed is an array of district ids. I got Unknown column 'districts.id' error. It was so easy if district_id was present at division table. How can I get such data at this situation?
Try this
$divisionWithDistricts = Division::with(['districts' => function($query) use($districtsAlreadyUsed) {
$query->whereNotIn('id', $districtsAlreadyUsed);
}])
->get();

Laravel inject SQL Query into Model Collection

I have a Laravel Controller method with the following code:
$listings = LikedListing::where('user_id', '=', $user->id)
->with('Listing.Photos')
->get();
This should return a collection of LikedListing records with Photos attached to each likedlisting record.
I have this SQL Query I need to inject into each record as well:
select u.id, l.address, u.first_name, u.last_name, ll.score
from listings l
left join liked_listings ll on ll.listing_id = l.id
left join users u on u.id = ll.user_id
where u.id in (
select secondary_user
from user_relationships
where primary_user = $primaryUser
)
and ll.listing_id = $listingId
Where $primaryUser = $user->id And $listingId is equal to the listingid inside each record in the collection.
I have absolutely no idea how to do this.
Maybe theres a model way of performing this? UserRelationship model has a primary_user column, which connects to a $user->id, and there is a secondary_user column, which acts like a follower userid, which is what we need in the final result (a list of all related users per listing)`
Can someone who has much far superior knowledge with Laravel please assist
My goal is to have the current collection of listing records with associated photos as well as following users (secondary_user) from the user_relationship table related to the primary_user (the logged in user) who have a record using user_id with the secondary_user value for that listing in the likedlisting table (obv assoicated with the listing_id). I already provided a raw sql query if thats the only option.
So in simple terms all related users who have liked a listing that the primary user has liked as well should be added to each listing record

Getting data from multiple tables via Laravel Eloquent

I have three tables; rate_params, review_form_languages, and review_form_translations. And corresponding models RateParam, ReviewFormLanguage and reviewFormTranslation.
rate_params has columns id, info_message, order and validation.
review_form_languages has id and name
review_form_translations has id, rate_params_id, review_form_languages_id, and text.
I would like to have query that fetches all the data from rate_params and the text from review_form_translations where review_form_languages.name is the passed parameter.
I have a query that fetches all the data from RateParam model as below
$reviewForm = RateParam::select(
'rate_params.id',
'rate_params.validation',
'rate_params.info_message',
)->orderBy('order', 'asc')->get()->toArray();
How do I join to get the text from review_form_translations where review_form_languages.name is the passed parameter?
Can you try this ,
use DB; // Top of the file
$reviewForm = DB::table('rate_params')
->join('review_form_translations','rate_params.id','=','review_form_translations.rate_params_id')
->join('review_form_languages','review_form_languages.id','=','review_form_translations.review_form_languages_id')
->orderBy('rate_params.order', 'asc')
->get()
->toArray();

Codeigniter: Selecting different columns from 3 tables

Today i encountered a problem developing my app.
I restructured my database.
I have 3 tables for posts, photos, and for the tags of the posts.
I joined the two other tables(photos, tags).
I would like to query the first 3 post with only one SELECT with photos and tags, but only the first row showing up from the results.
Heres is my code:
$this->db->select('owner, title, time, LEFT(content, 75) as content, category, url, price, county');
$this->db->from(POSTS_TABLE);
$this->db->join(PHOTOS_TABLE, PHOTOS_TABLE.'.post_id = '.POSTS_TABLE.'.url');
$this->db->join(TAGS_TABLE, TAGS_TABLE.'.post_url = '.POSTS_TABLE.'.url');
$this->db->order_by('time', 'desc');
$this->db->limit(3);
$query = $this->db->get();
$posts = $query->result();
My DB structure:
posts table:
id, owner, title, content, url
tags table: id, post_id (same as the url column from the posts table), photo (the link to the photo)
tags table:
id, post_url (same as the url column from the posts table), tag.
Please help.How can i achieve that with only one SELECT and showing up the correct results ?
I cannot use the WHERE clause, since i dont know the exact post_url
Considering column name 'url' is the id of the row
Try:
// Code before
$this->db->join('PHOTOS_TABLE', 'PHOTOS_TABLE.post_id = POSTS_TABLE.url');
$this->db->join('TAGS_TABLE', 'TAGS_TABLE.post_url = POSTS_TABLE.url');
// Code After

Resources