Codeigniter: Selecting different columns from 3 tables - codeigniter

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

Related

Laravel Eloquent - Getting data from related models and apply union doesn't work

Faced a really strange error and can't understand why it's happening. Please see the explanation below to understand the issue!
What I have:
3 models: Bucket, Template and DesignPack.
Bucket has Many-To-Many(Polymorphic) relationship with Template and DesignPack(It means we have pivot table bucketables).
In essence Bucket can have(be related with) both: Template and DesignPack.
Laravel 6.*
What I want to do:
I want to get all Bucket's Template and DesignPack models merged(using union) with specific columns only. Want to get it with pagination also off course as we can have too many items :)
What I did:
I tried a few solutions but none of the worked, had the same errors. Please see example below what I've tried:
$templates = Bucket::find($bucket_id)->templates()->select('id', 'file_name as name', 'size', 'preview');
$design_packs = Bucket::find($bucket_id)->dps()->select('id', 'name', 'size', 'preview');
$bt_uploads = $templates->union($design_packs)->paginate(20);
return UserUploadResource::collection($bt_uploads);
The error I get constantly is:
"SQLSTATE[21000]: Cardinality violation: 1222 The used SELECT
statements have a different number of columns (SQL: select count() as
aggregate from ((select id, file_name as name, size,
preview, templates., bucketables.bucket_id as
pivot_bucket_id, bucketables.bucketable_id as
pivot_bucketable_id, bucketables.bucketable_type as
pivot_bucketable_type from templates inner join bucketables on
templates.id = bucketables.bucketable_id where
bucketables.bucket_id = 3 and bucketables.bucketable_type =
App\Template and templates.deleted_at is null) union (select id,
name, size, preview from design_packs inner join bucketables
on design_packs.id = bucketables.bucketable_id where
bucketables.bucket_id = 3 and bucketables.bucketable_type =
App\DesignPack and design_packs.deleted_at is null)) as
temp_table)"
Many thanks guys for any help and ideas!

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();

Laravel Many To Many Get Fields From Both Tables

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',
]);

Magento - filtering customers based on an EAV (custom) attribute in RMA Grid

I am using Magento 1.4.1.1 and the AW RMA extension over it.
With this extension installed I see an RMA requests grid and Pending RMA requests grid in admin.
I want to be able to filter requests in this grid based on an EAV (custom) attribute e.g., customer_referrer_id which is stored in customer_entity_varchar
The extension has a table aw_rma_entity in which it also keeps customer_id. The RMA Grid fetches data like this:
$collection = Mage::getModel('awrma/entity')
->getCollection();
ATTEMPT 1
I have attempted to join the customer entity with this table as follows:
$collection->getSelect()->join('customer_entity', 'customer_id = customer_entity.entity_id', array('entity_id' => 'customer_entity.entity_id'));
RESULT 1
This just shows a page with no grid. If it had worked I would have then attempted to join customer_entity_varchar to apply the filter on the customer_referrer_id field.
ATTEMPT 2
The other attempt I have made is to load the customer collection first and then join RMA entity data to it as in the following code:
$collection = Mage::getResourceModel('customer/customer_collection');
$collection->joinRight('awrma/entity', 'customer_id=entity_id', array('*'));
RESULT 2
The second attempt generates the following error:
Error Message--------------------------------> Item
(Mage_Customer_Model_Customer) with the same id "XXX" already exist";
This is despite of the fact that it had worked for me earlier in this way after a similar question for filtering results in the Sales Orders Grid
This is probably not the best solution, but it will most likely work:
$collection = Mage::getModel('awrma/entity')->getCollection();
$collection->getSelect()->joinInner('customer_entity_varchar', 'customer_id=entity_id', array('attribute_id' =>'attribute_id','value'=>'value') );
$logged_in_admin = Mage::getSingleton('admin/session')->getUser()->getEmail();
$customer_referrer_attribute_id = //Set this equal to attribute_id FROM table eav_attribute WHERE attribute_code = "customer_referrer_id"
$collection->addFieldToFilter('attribute_id', $customer_referrer_attribute_id );
$collection->addFieldToFilter('value', $customer_referrer_id);

Resources