Codeigniter 4 ORM relation By hand
Add ModelTrait file at \App\Traits
namespace App\Traits;
trait ModelTrait
{
// fetaure Maybe belongsTo
// get result but not effect this, keep this ORM status
public function newSelfObject()
{
return $this->db->query($this->builder->getCompiledSelect(false));
}
public function hasOne($class, $relation_primary_key=null, $primary_key=null)
{
return $class->where($relation_primary_key ?? $this->primaryKey, $this->newSelfObject()->getRowArray()[$primary_key ?? $this->primaryKey] ?? '');
}
// whereIn If can't get records, return null. Usually use primaryKey cloud happen
public function hasMany($class, $relation_primary_key=null, $primary_key=null)
{
$temp = array_column($this->newSelfObject()->getResult(), $primary_key ?? $this->primaryKey);
return $class->whereIn($relation_primary_key ?? $this->primaryKey, empty($temp) ? [null] : $temp);
}
}
How to use
App\Models\Order.php
class Order extends Model
{
use ModelTrait;
protected $table = 'order';
protected $primaryKey = 'order_id';
public function members()
{
return $this->hasMany(new Member);
// OR
return $this->hasMany(new Member, 'id', 'member_id'); // id always use new Member, member_id use Order
}
App\Controllers\OrderListContriller.php
namespace App\Controllers\Order;
class OrderListController extends \App\Controllers\BaseController
{
public function OrderList()
{
// 1. one order
$members = (new Order)->where('id', $order_id)->members()->first(); // ->findAll();
// 2. All orders
$members = (new Order)->members()->findAll();
// 3.
$order = (new Order)->where("id", $order_id);
$orderData = $order->newSelfObject()->getRow(); // Maybe need orderData to do something.
$member = $order->members()->where('createtime >', '2022/11/22')->first(); // ->findAll();
}
}
You can make belongTo or belongsTo by yourself. More about feature like multiple key, it’s more complex