I got in trouble trying to get data from two MySQl table.
In the first table I stored image filename; in the second table I stored info about each image; info are in two languages, en and it. Of course not all images in first table have info in the second one.
I'm trying to get images an info for a selected language in the following way:
$this->db->select ('
tbl_images.image,
tbl_infos.info
');
$this->db->from('tbl_images');
$this->db->join('tbl_infos', 'tbl_images.id = tbl_infos.id', 'left');
$this->db->where('tbl_images.id', $id);
$this->db->where('tbl_infos.lang', 'en');
Now...if the tbl_infos table has text, the query return correct data, but if no info are stored I get an error since no images are retrieved; if I remove the lang where clause I get the iamge if no info are stored...but I get images with info twice!!
I'm getting crazy and completely stuck on this...how can I fix this?
Thanks a lot
try this
$this->db->join('tbl_infos', 'tbl_images.id = tbl_infos.id');
Silly me...I got fixed writing the second condition in the same JOIN row.
So, the following JOIN:
$this->db->join('tbl_infos', 'tbl_images.id = tbl_infos.id', 'left');
becomes:
$this->db->join('tbl_infos', 'tbl_images.id = tbl_infos.id AND tbl_infos.lang = "en"', 'left');
Related
I am struggling to get list of places that matches current category(multiple dataset) and city:
what i did is the following,
$cat = Category::find($request->category_id)->toArray();
$cat_id = $cat['id'];
and
$places = DB::table('places')
->where('category',$cat_id)
->where('city_id', $request->city_id)
->get();
See screenshot of the dataset:
Data in the database
For your current problem, you can use the LIKE operator.
$places = DB::table('places')
->where('category','LIKE', '%"'.$cat_id.'"%')
->where('city_id', $request->city_id)
->get();
but the above code will not solve your problem permanently. It looks like you are trying to create a many to many relationship in this case the best practice to use pivot tables for this. Better if you could update the schema as an example and follow the Laravel standards to achieve this. Example:
table: category_place , having columns ["category_id", "place_id"]
in the same way, you need to update the following schema
Place Type
table: place_place_type, columns ["place_id", "place_type_id"]
Amenities
table: amenity_place, columns ["amenity_id", "place_id"]
Ref. link: https://laravel.com/docs/8.x/eloquent-relationships#many-to-many-polymorphic-relations
i'm trying to select and insert values into a database with eloquent models. The thing is, i made a query to get a value from another table and insert it in the new one. But it keeps inserting 0 when it should insert the value of the id that i'm retrieving
This is the way i'm selecting the id from table clients:
$client_id = Client::select('id')->where('dni', '=', $request->client)->first();
\Log::debug($client_id);
The debug on the Log returns this:
[2020-08-05 17:43:25] local.DEBUG: {"id":1}
And this is the insert:
$seguro = new Seguro();
$seguro->usuario_id = $user_id;
$seguro->cliente_id = $client_id;
$seguro->save();
And the insert is successfull except for the column cliente_id where i'm getting 0 instead of 1.
Can anyone help me with this?
Your $client_id contains object (model), not integer value. You can even see this in debug. Just get id from this model using ->id
$seguro->cliente_id = $client_id->id; // also better change name $client_id to $client
or
$client_id = Client::select('id')->where('dni', '=', $request->client)->first()->id;
Also it is good idea to write code in english (variable names). For example I do not know what "dni" should mean in this query.
Link for table
link for expected result, after group by 'receiver_user_id' and recent time
I have used the laravel query:-
$sub = BaseMessagesHistory::select('messages_history.*')->orderBy('created_at','DESC');
$chats = DB::table(DB::raw("({$sub->toSql()}) as sub"))
->select('receiver_user_id',DB::raw('max(created_at) as recent_time'))
->where('sender_user_id',$userId)
->orwhere('receiver_user_id',$userId)
->groupBy('receiver_user_id')
->havingRaw('max(created_at)')
->latest()->get();
Result:-
I am getting only "recent_time" and "receiver_user_id"
Expectation:- I need whole data from table not only "recent_time" and "receiver_user_id"
So can you please help me out
It will return you only those columns which you mentioned in the select().
In your query, you mentioned only receriver_user_id and recent_time.
->select('receiver_user_id',DB::raw('max(created_at) as recent_time'))
You need to add all those columns in select() which you need.
Or try this ->select('sub.*',DB::raw('max(created_at) as recent_time'))
Hope this helps. Ask in case of doubt.
I am writing a Plugin and added a own db table to the magento database.
Now i want to get some data in sorted order from the table and i added the code bellow.
But everytime i dump the result of the last line i get the data in the order they are in the table not sorted by the given parameter. Can anyone help me with this?
$collection = $this->getCollection();
$collection->setOrder(array('fieldname' => 'asc', 'fieldname' => 'desc'));
$collection->getFirstItem()->getData();
You can call setOrder function multiple times for different columns.
$collection = $this->getCollection()
->setOrder('fieldname', 'asc')
->setOrder('fieldname2');
Note: Direction DESC will be used by default.
I have been trying to join two custom table using magento's commands. After searching i came across this block of generic code
$collection = Mage::getModel('module/model_name')->getCollection();
$collection->getSelect()->join( array('table_alias'=>$this->getTable('module/table_name')),
'main_table.foreign_id = table_alias.primary_key',
array('table_alias.*'),
'schema_name_if_different');
Following this as template I have tried to join my tables together but have only returned errors such as incorrect table name or table doesn't exist or some other error.
Just to clear things up can someone please correct me on my understanding
$collection = Mage::getModel('module/model_name')->getCollection();
Gets an instance of your model. Within that model is the table that holds the required data (for this example I shall call the table p)
$collection->getSelect()
Select data from table p
->join()
Requires three parameters to join two table together
PARAM1
array('table_alias'=>$this->getTable('module/table_name'))
'the alised name you give the table' => 'the table you want to add to the collection (this has been set up in the model folder)'
PARAM2
'main_table.foreign_id = table_alias.primary_key'
This bit i don't get (it seems straight forward though)
my main table (p) doesn't have a foreign id (it has it's primary key - is that also its foreign id)?
has to be equal to the alised name you gave in param1
PARAM3
'main_table.foreign_id = table_alias.primary_key'
get all from alised name
Where have I gone wrong on my understanding?
Please have a look in below sql join statement, I am using it in my project and it is working perfectly.
Syntax
$collection = Mage::getModel('module/model_name')->getCollection();
$collection->getSelect()->join(Mage::getConfig()->getTablePrefix().'table_name_for_join', 'main_table.your_table_field ='.Mage::getConfig()->getTablePrefix().'table_name_for_join.join_table_field', array('field_name_you_want_to_fetch_from_db'));
Working Query Example
$collection = Mage::getModel('module/model_name')->getCollection();
$collection->getSelect()->join(Mage::getConfig()->getTablePrefix().'catalog_product_entity_varchar', 'main_table.products_id ='.Mage::getConfig()->getTablePrefix().'catalog_product_entity_varchar.entity_id', array('value'));
Hope this will work for you !!