ActiveRecord where and order on via-table

ActiveRecord where and order on via-table

By : ElusiveNapkin
Date : November 15 2020, 06:54 AM
wish of those help Using via and viaTable methods with relations will cause two separate queries.
You can specify callable in third parameter like this:
code :
public function getAdvantages()
    return $this->hasMany(AdvantageModel::className(), ['id' => 'advantage'])
        ->viaTable('product_has_advantage', ['product' => 'id'], function ($query) {
            /* @var $query \yii\db\ActiveQuery */

            $query->andWhere(['important' => 1])
                ->orderBy(['sort' => SORT_DESC]);
public function getAdvantages()
    return $this->hasMany(AdvantageModel::className(), ['id' => 'advantage'])
        ->viaTable('product_has_advantage', ['product' => 'id'])
        ->andWhere(['important' => 1])
        ->orderBy(['sort' => SORT_DESC]);

Share : facebook icon twitter icon
Rails activerecord order by field in related table

Rails activerecord order by field in related table

By : user2986199
Date : March 29 2020, 07:55 AM
Yii2 Activerecord get fields from junction table and order by according to them

Yii2 Activerecord get fields from junction table and order by according to them

By : Amit Kr Rastogi
Date : March 29 2020, 07:55 AM
wish help you to fix your issue Finally I have found a solution. It depends on findBySql method. I'm going to use the above SQL query regarded in Update 2 -just I have removed some selected fields to be suitable for my current task-.
code :
public function actionUnitsJson($id){    
$sql = 'SELECT units.id, units.title 
    FROM units
     Left JOIN item_units AS iu
      ON iu.item_id = :id AND iu.unit_id = units.id 
        units.id = iu.unit_id 
    ORDER BY iu.weight DESC;';

          $units = \common\models\Units::findBySql($sql,[':id' => $id])->asArray()->all();
    return Json::encode($units);
activerecord - order by two associations from the same table

activerecord - order by two associations from the same table

By : open
Date : March 29 2020, 07:55 AM
Hope that helps When you join on the same table twice, using different foreign keys, ActiveRecord goes ahead and aliases all but the first table for you. So while you can reference the flying_airline relation with airlines in SQL, this won't work for the rest.
The alias created is the pluralized name of the AR relation you are joining (home_airlines) prepended to the pluralized class name of the table being joined on (route_pairs). So in this case, the alias would be home_airlines_route_pairs.
code :
RoutePair.joins(:flying_airline, :home_airline).order('home_airlines_route_pairs.name')
RoutePair.joins(:flying_airline, :home_airline).order('airlines.name asc, home_airlines_route_pairs.name asc')
RoutePair.joins(:flying_airline, :home_airline).to_sql
ActiveRecord: Order table based on the average of an association's column

ActiveRecord: Order table based on the average of an association's column

By : Andrea Dejan Grande
Date : March 29 2020, 07:55 AM
wish of those help I am building a system for job seekers to track jobs their interested in using Rails. I want to rank companies based on the user's level of interest in the company as determined by averaging the user-declared 'level of interest' in each job posted by the company. So, for example, Wal Mart might post 3 jobs, and the user would submit their level of interest for each of those jobs, and we'd calculate the overall interest in Wal Mart by averaging those 3 levels of interest. There will be several companies with several jobs. , Something like this should work:
code :
Company.select('companies.id, avg(jobs.level_of_interest)')
       .order('avg(jobs.level_of_interest) desc')
Sort order for ActiveRecord::Associations::CollectionProxy in table rails

Sort order for ActiveRecord::Associations::CollectionProxy in table rails

By : user127858
Date : March 29 2020, 07:55 AM
this one helps. I would add a class method on the Room model in order to return for a given collection the number of free rooms and reserved rooms:
code :
class Room < ApplicationRecord
  belongs_to :hotel, optional: true
  accepts_nested_attributes_for :hotel

  def self.reserved_count
    where(reserved: true).count

  def self.free_count
    where(reserved: false).count
class Hotel < ApplicationRecord
  has_many :rooms, dependent: :destroy
  accepts_nested_attributes_for :rooms

  def reserved_rooms

  def free_rooms
    <th>Rooms count</th>
    <th>Rooms status: in reserved || free</th>    

  <% @hotels.each do |hotel| %>
      <td><%= hotel.name %></td>
      <td><%= hotel.rooms_count %></td>
      <td><%= "#{hotel.reserved_rooms} || #{hotel.free_rooms}" %></td>      
      <td ><%= link_to 'Show', hotel_path(hotel) %></td>
      <td><%= link_to 'Destroy', hotel, method: :delete, data: { confirm: 'Are you sure?' } %>
  <% end %>
@hotels = Hotel.includes(:rooms).sort_by { |h| h.free_rooms.to_i }.reverse
Related Posts Related Posts :
  • Property 'throw' does not exist on type 'typeof Observable'
  • Unable to deploy SAPUI5 application with 404 error
  • Xcode 10 build fail rm permission denied in /bin/sh/
  • Handling quorum writies fail on Cassandra
  • How to finalize log file just after time is over when using logback SizeAndTimeBasedFNATP?
  • Write custom widget with GTK3
  • How to remove UINavigationBar inner shadow in iOS 7?
  • Wordpress dynamic widget by location?
  • XDocument replace all node value with lower case
  • Invalid tagdir attribute while web-fragment is used
  • Set default font/text size in RTF Control
  • what video formats supported by chromecast device (mp4,flv,m3u8,flv,avi)?
  • sbcl - how to muffle "undefined variable" warning?
  • Get an eventbrite event ID
  • Obtain date without timestamp in DB2
  • Cron job to SFTP files in a directory
  • Draw two head arrows in fabric.js
  • YOLO darknet vs darkflow
  • Parse custom rss tags using Rome API
  • Creating text editor like EDIT on Command Prompt using FreePascal
  • Subplot hides xlabel
  • NServiceBus long running process that timesout
  • Qt4 - How to add a row in a QTableWidget when sorting is enable?
  • Cancel command in Grunt that hasn't been launched
  • Canvas globalCompositeOperation is not working correctly
  • HTML.Kendo().Dropdownlist set default item
  • vagrant up failed, /dev/vboxnetctl: no such file or directory
  • How to use jssor carousel to build client carousal
  • Theory what is meant by validating security concerns for these user groups
  • How to build correct SPARQL Query
  • Connecting to MySQL (on Google Cloud SQL) via JDBC and IPv6?
  • Fetching transaction in several iterations
  • is it possible to use dropbox datastore api as shared datastore?
  • phpExcel 1.8 Named Ranges in Formula
  • Cisco VPN IP address
  • No address associated with hostname using vagrant
  • 2 way data-binding between a polymer component and a model?
  • How can I rename an already published app in the Windows Dev Center?
  • Using Chef 12 , Chef Client unable to connect to chef Server
  • GCM notification not working (GoogleCloudMessaging)
  • Measured GFLOPS is greater then theoretical GFLOPS
  • Progress ABL - strip and add to temp table
  • Errors occuring when make-ing Aircrack-ng on raspberry pi
  • Detecting Handedness from Device Use
  • Query a manual list of data items
  • Similar to pivot - Windows 8.1 Desktop app
  • CKEDITOR And Styles configuration with only toolbar
  • Segmentation fault due to data alignment issue on MIC
  • how to connect a Java app ( java code ) to cloudant?
  • How to download a file/folder from remote (openshift) to local system
  • Where can i find customeditors in JBPM 6
  • Pig get distinct rows with counts
  • In Flex when is yylineno updated?
  • How does a semantic reasoner for protegé is made?
  • how to stop another rows to be select after select a row in uitableview
  • Setup cmd.exe parameter when starting ConEmu
  • WPF how to get the same visual size in different devices
  • How to convert tiff to searchable pdf using alfresco and tesseact?
  • Intel Media SDK: Regarding mfxIMPL Usage
  • How to pass values to SOAP service using web service consumer?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org