M
M
Mikha Pankratov2015-12-14 11:00:22
Yii
Mikha Pankratov, 2015-12-14 11:00:22

What is the correct way to select with hasMany()?

Good afternoon,
I organized a connection in the database and generated hasMany () in the model

class Day extends \yii\db\ActiveRecord
{
public function getXxx()
    {
        return $this->hasMany(\app\models\xxx::className(), ['days_id' => 'id']);
    }

How can I get a connected array in the controller?
\app\models\Day::getXxx();
Calling unknown method: app\modules\caregiver\controllers\MyController::hasMany()

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Natarov, 2015-12-14
@HanDroid

1) Relationships are declared at two ends example:

class Customer extends ActiveRecord
{
    public function getOrders()
    {
        return $this->hasMany(Order::className(), ['customer_id' => 'id']);
    }
}

class Order extends ActiveRecord
{
    public function getCustomer()
    {
        return $this->hasOne(Customer::className(), ['id' => 'customer_id']);
    }
}

2) Getting connected data
// SELECT * FROM `customer` WHERE `id` = 123
$customer = Customer::findOne(123);

// SELECT * FROM `order` WHERE `customer_id` = 123
// $orders - это массив объектов Order
$orders = $customer->orders;

3) The principle of obtaining an array of objects. Second option to continue query like ->where(blah blah)
$customer->orders; // массив объектов `Order`
  $customer->getOrders(); // объект ActiveQuery

V
Vit, 2015-12-14
@fornit1917

$day = Day::findOne($dayId); //get day
$xxx = $day->getXxx()->all(); //get related data

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question