Laravel - how to eager load relation of custom intermediate table - php

I have three models, SalesReturn, Product and ProductSalesReturn, and their relations are following:
class SalesReturn extends Model
{
public function products()
{
return $this->belongsToMany(Product::class)
->withTimestamps()
->using(ProductSalesReturn::class);
}
}
I use the ProductSalesReturn to represent the intermediate table ( https://laravel.com/docs/6.x/eloquent-relationships#defining-custom-intermediate-table-models ), and ProductSalesReturn has a relation to Unit:
class ProductSalesReturn extends Pivot
{
public function unit()
{
return $this->belongsTo(Unit::class);
}
}
When I eager loading the unit relation like following code:
SalesReturn::with(['products', 'products.unit'])->find($id);
I will get the following error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'units.product_id' in 'where clause' (SQL: select * from `units` where `units`.`product_id` in (1031, 1631, 13391, 14361, 16981, 17441, 41982, 45982, 55741) and `units`.`deleted_at` is null)
The table schemas are following:
CREATE TABLE `sales_returns` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`number` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
`user_id` bigint(20) NOT NULL,
`order_id` bigint(20) NOT NULL,
`note` text COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `product_sales_return` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`sales_return_id` bigint(20) NOT NULL,
`product_id` bigint(20) NOT NULL,
`unit_id` bigint(20) NOT NULL,
`price` double NOT NULL,
`amount` int(11) NOT NULL,
`gross_profit` double NOT NULL DEFAULT '0',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
How can I eager loading the relation of custom intermediate table in Laravel ?
Thank you.

You could use Laravel Eloquent: Eager Load Pivot Relations
Installation
composer require ajcastro/eager-load-pivot-relations
Configuration
use AjCastro\EagerLoadPivotRelations\EagerLoadPivotTrait;
class Product extends Model
{
// Use the trait here to override eloquent builder.
// It is used in this model because it is the relation model defined in
// SalesReturn::products() relation.
use EagerLoadPivotTrait;
}
Usage
return SalesReturn::with('products.pivot.unit')->get();
Define the table, foreignPivotKey and relatedPivotKey paramethers in your produtcts belongsToMany relationship

Related

How to access to sub related model when the related model returns a collection

I have 3 models: User, Payment and Log. A User has many Payment and both User and Payment have many Log.
User Model
class User
{
public function payments()
{
return $this->hasMany('Payment', 'user_id');
}
public function logs()
{
return $this->morphMany(Log::class, 'loggable');
}
}
users table
CREATE TABLE `users` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`email_verified_at` timestamp NULL DEFAULT NULL,
`password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `users_email_unique` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Payment Model
class Payment
{
public function user()
{
return $this->belongsTo('User', 'user_id');
}
public function logs()
{
return $this->morphMany(Log::class, 'loggable');
}
}
payments table
CREATE TABLE `payments` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`status` varchar(50),
`amount` int(11) NOT NULL,
`collection_date` date NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`user_id` bigint(20) unsigned NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `fk_payments_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Log Model
class Log
{
public function loggable()
{
return $this->morphTo();
}
}
logs table
CREATE TABLE `logs` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`loggable_type` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`loggable_id` bigint(20) unsigned NOT NULL,
`old_values` text COLLATE utf8mb4_unicode_ci,
`new_values` text COLLATE utf8mb4_unicode_ci,
`user_id` bigint(20) unsigned DEFAULT NULL, /* the user that made the change, if any */
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
The Log model stores all changes made to any other model (it's a polymorphic relationship), so if the user changes its name, the Log model will store the older name and the new name. The same applies to Payment: if a payment status changes the Log model will have a new record with the old status and the new status.
I need to show a paginated list of all Log records for a specific User ordered by date. So my code is:
$user = App\User::find($id);
$allLogs = $user->logs();
// Now I need to join (I'm using union) both sets of logs
$allLogs->union($user->payments->logs());
However, since a User can have many Payment, $user->payments returns a Collection, so is no longer a query builder/eloquent object and it fails when I try to call ->logs().
$user->payments()->logs() also doesn't work, because $user->payments() returns a HasMany object and the ->logs() method doesn't exist.
I'm trying to avoid getting each collection of Log separately and then processing them using php (it would be perfect to delegate that task to MySql).
I believe it can be done, because I can write the query on MySql:
select l.*
from payments p
join logs l on p.id = l.loggable_id and l.loggable_type = 'App\\Payments'
where p.user_id = SOMEUSERID
Thanks in advance
Eager load the relations(reduces number of queries)
$user = User::with(['payments.logs', 'logs'])->find($id);
Query using the Log model.
$logs = Log::where([
'loggable_id' => $user->id,
'loggable_type' => 'User',
])
->orWhere(function($query){
$query->whereIn('loggable_id',
$user->payments()->pluck('id'))
->where('loggable_type', 'Payment');
})->get();
OR
Get them individually and then combine them.
$all_logs = collect([]);
$all_logs->push($user->logs);
foreach($user->payments as $p){
$all_logs->push($p->logs);
}
$final_logs = $all_logs->collapse();
OR
Just use the relations, without iterating over the payments. You can combine the results if you want(as shown in the previous approach).
$user_logs = $user->logs;
$payment_logs = $user->payments->pluck('logs')->collapse();

Laravel eager loading error "Trying to get property of non-object in .../BelongsToMany.php"

Laravel 5.8
I'm having an issue getting eager loading to work on some models but not on others.
Using artisan tinker I can run;
$p = App\Programme::find(34)->reviews
and get the correct result. If I change this to;
$p = App\Programme::with('reviews')->find(34)
So that the reviews are eager loaded, it fails with the error
PHP Notice: Trying to get property of non-object in .../vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php on line 301
output from artisan with query log, bindings and execute time
$p = App\Programme::with('destinations', 'reviews')->find(34)
"select * from `programmes` where `programmes`.`id` = ? and `programmes`.`deleted_at` is null limit 1"
array:1 [
0 => 34
]
1.08
"select `destinations`.*, `programme_destination`.`programme_id` as `pivot_programme_id`, `programme_destination`.`destination_id` as `pivot_destination_id`, `programme_destination`.`created_at` as `pivot_created_at`, `programme_destination`.`updated_at` as `pivot_updated_at` from `destinations` inner join `programme_destination` on `destinations`.`id` = `programme_destination`.`destination_id` where `programme_destination`.`programme_id` in (34)"
[]
0.88
"select `reviews`.*, `programme_reviews`.`programme_id` as `pivot_programme_id`, `programme_reviews`.`review_id` as `pivot_review_id`, `programme_reviews`.`created_at` as `pivot_created_at`, `programme_reviews`.`updated_at` as `pivot_updated_at` from `reviews` inner join `programme_reviews` on `reviews`.`id` = `programme_reviews`.`review_id` where `programme_reviews`.`programme_id` in (34)"
[]
0.85
The final query if run manually works just fine.
I can run the exact same two commands using either the User or Destination models and get a successful response. So there must be something different about the relationship of $programme->reviews when compared to $programme->user or $programme->destinations
Here are my models (trimmed to the relevant functions);
App\BaseModel
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use OwenIt\Auditing\Contracts\Auditable;
use Log;
use DB;
class BaseModel extends Model
{
protected $guarded = ['alias', 'created_at', 'updated_at', 'deleted_at', 'slug'];
public $custom_attributes = [];
public $index_attributes = ['alias', 'user'];
public function alias()
{
return $this->morphOne('App\Alias', 'aliased');
}
public function user()
{
return $this->belongsTo('App\User');
}
}
App\Programme
<?php
namespace App;
use App\BaseModel;
use Illuminate\Database\Eloquent\SoftDeletes;
use OwenIt\Auditing\Contracts\Auditable;
use Log;
class Programme extends BaseModel implements Auditable
{
use SoftDeletes;
use \OwenIt\Auditing\Auditable;
protected $table = 'programmes';
protected $dates = ['deleted_at'];
function __construct(array $attributes = array())
{
parent::__construct($attributes);
}
public function destinations()
{
return $this->belongsToMany('App\Destination', 'programme_destination')
->withTrashed()
->withTimestamps();
}
public function reviews()
{
return $this->belongsToMany('App\Review', 'programme_reviews')
->withTrashed()
->withTimestamps();
}
}
App\Review
<?php
namespace App;
use App\BaseModel;
use Illuminate\Database\Eloquent\SoftDeletes;
use OwenIt\Auditing\Contracts\Auditable;
use Log;
class Review extends BaseModel implements Auditable
{
use SoftDeletes;
use \OwenIt\Auditing\Auditable;
protected $fillable = ['title', 'name', 'first_name', 'last_name', 'review_type', 'email_address', 'created_at'];
function __construct(array $attributes = array())
{
parent::__construct($attributes);
}
public function programmes()
{
return $this->belongsToMany('App\Programme', 'programme_reviews')
->withTrashed()
->withTimestamps();
}
}
I can run $p = App\Programme::with('destinations', 'alias')->find(34) successfully. Here's the model for destinations
App\Destination
<?php
namespace App;
use App\BaseModel;
use Illuminate\Database\Eloquent\SoftDeletes;
use OwenIt\Auditing\Contracts\Auditable;
class Destination extends BaseModel implements Auditable
{
use SoftDeletes;
use \OwenIt\Auditing\Auditable;
protected $table = 'destinations';
protected $dates = ['deleted_at'];
function __construct(array $attributes = array())
{
parent::__construct($attributes);
}
public function programmes()
{
return $this->belongsToMany('App\Programme', 'programme_destination')
->withTrashed()
->withTimestamps();
}
}
It seems the relationship works based on the first artisan command, so why does this not work when eager loading?
For reference here are the database create codes;
programmes
CREATE TABLE `programmes` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(191) NOT NULL COLLATE 'utf8_unicode_ci',
`destination_id` INT(10) UNSIGNED NULL DEFAULT NULL,
`user_id` INT(10) UNSIGNED NOT NULL DEFAULT '1',
`created_at` TIMESTAMP NULL DEFAULT NULL,
`updated_at` TIMESTAMP NULL DEFAULT NULL,
`deleted_at` TIMESTAMP NULL DEFAULT NULL,
PRIMARY KEY (`id`),
INDEX `programmes_user_id_foreign` (`user_id`),
INDEX `programmes_destination_id_foreign` (`destination_id`),
CONSTRAINT `programmes_destination_id_foreign` FOREIGN KEY (`destination_id`) REFERENCES `destinations` (`id`),
CONSTRAINT `programmes_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
)
COLLATE='utf8_unicode_ci'
ENGINE=InnoDB
;
reviews
CREATE TABLE `reviews` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`title` VARCHAR(191) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
`name` VARCHAR(191) NOT NULL COLLATE 'utf8_unicode_ci',
`first_name` VARCHAR(191) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
`last_name` VARCHAR(191) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
`email_address` VARCHAR(191) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
`created_at` TIMESTAMP NULL DEFAULT NULL,
`updated_at` TIMESTAMP NULL DEFAULT NULL,
`deleted_at` TIMESTAMP NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
COLLATE='utf8_unicode_ci'
ENGINE=InnoDB
;
programme_reviews - many to many
CREATE TABLE `programme_reviews` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`programme_id` INT(10) UNSIGNED NOT NULL,
`review_id` INT(10) UNSIGNED NOT NULL,
`created_at` TIMESTAMP NULL DEFAULT NULL,
`updated_at` TIMESTAMP NULL DEFAULT NULL,
PRIMARY KEY (`id`),
INDEX `programme_reviews_review_id_foreign` (`review_id`),
INDEX `programme_id` (`programme_id`),
CONSTRAINT `programme_reviews_programme_id_foreign` FOREIGN KEY (`programme_id`) REFERENCES `programmes` (`id`) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT `programme_reviews_review_id_foreign` FOREIGN KEY (`review_id`) REFERENCES `reviews` (`id`) ON UPDATE CASCADE ON DELETE CASCADE
)
COLLATE='utf8_unicode_ci'
ENGINE=InnoDB
;
destinations
CREATE TABLE `destinations` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(191) NOT NULL COLLATE 'utf8_unicode_ci',
`user_id` INT(10) UNSIGNED NOT NULL DEFAULT '1',
`created_at` TIMESTAMP NULL DEFAULT NULL,
`updated_at` TIMESTAMP NULL DEFAULT NULL,
`deleted_at` TIMESTAMP NULL DEFAULT NULL,
PRIMARY KEY (`id`),
INDEX `destinations_parent_id_index` (`parent_id`),
INDEX `destinations_user_id_foreign` (`user_id`),
CONSTRAINT `destinations_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
)
COLLATE='utf8_unicode_ci'
ENGINE=InnoDB
;
programme_destinations one to many
CREATE TABLE `programme_destination` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`programme_id` INT(10) UNSIGNED NOT NULL,
`destination_id` INT(10) UNSIGNED NOT NULL,
`created_at` TIMESTAMP NULL DEFAULT NULL,
`updated_at` TIMESTAMP NULL DEFAULT NULL,
PRIMARY KEY (`id`),
INDEX `programme_destination_programme_id_foreign` (`programme_id`),
INDEX `programme_destination_destination_id_foreign` (`destination_id`),
CONSTRAINT `programme_destination_destination_id_foreign` FOREIGN KEY (`destination_id`) REFERENCES `destinations` (`id`) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT `programme_destination_programme_id_foreign` FOREIGN KEY (`programme_id`) REFERENCES `programmes` (`id`) ON UPDATE CASCADE ON DELETE CASCADE
)
COLLATE='utf8_unicode_ci'
ENGINE=InnoDB
;
The only real difference between $programme->destinations and $programme->reviews is that reviews is a many to many relationship.
So I've found the answer to this niggling query thanks to outside help.
My question as is would not have been answerable, as the problem actually existed with a $pivot class variable I had assigned on the Programme model (and removed for the post to attempt to shorten it).
This variable clashed with Laravel's internal workings, which seems quite obvious now I know about it.
Changing $pivot to anything else allowed the relationship to be eager loaded correctly.
It's unlikely someone will have the same issue as me, but who knows, it may help someone avoid the error I encountered.
Just adding another answer in case it helps someone searching for this problem.
I just spent an hour trying to work out why I was getting "Trying to get property of non-object" when eager-loading a many-to-many relationship with
Document::where('id',$id)->with('authors')->first();
I tracked the problem down to the Document model which contained a pivot table alias and a specified pivot field:
public function authors() {
return $this->belongsToMany('App\User')->withPivot('role')->as('role');
}
When I swapped the order of the methods and renamed the alias, it worked.
public function authors() {
return $this->belongsToMany('App\User')->as('author_role')->withPivot('role');
}
The "Trying to get property of non-object" error was completely unhelpful in debugging this error. But making the change above was enough to resolve it.

How to remove a polymorphic relation in Eloquent?

I have a model like this:
<?php
class Post extends Eloquent {
protected $fillable = [];
public function photos()
{
return $this->morphMany('Upload', 'imageable');
}
public function attachments()
{
return $this->morphMany('Upload', 'attachable');
}
}
and my morphMany table's schema is like this:
CREATE TABLE `uploads` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`raw_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`size` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`downloads` int(11) NOT NULL DEFAULT '0',
`imageable_id` int(11) DEFAULT NULL,
`imageable_type` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
`attachable_id` int(11) DEFAULT NULL,
`attachable_type` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
`user_id` int(10) unsigned NOT NULL,
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`),
KEY `uploads_user_id_index` (`user_id`),
CONSTRAINT `uploads_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `posts` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=45 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
now I need to remove one row of this table, I tried $posts->photos()->delete(); but it removed all rows associated to this Post.
Could someone help me?
$posts->photos() is the relationship query to return all of the photos for a post. If you call delete() on that, it will delete all of those records. If you only want to delete a specific record, you need to make sure you only call delete on the one you want to delete. For example:
$posts->photos()->where('id', '=', 1)->delete();
to reomove from pivot table in many to many polymorphic relation just use detach:
$posts->photos($photoModel)->detach();
The relationship isn't even needed for this. Just use the Upload model directly:
Upload::find($id)->delete();
Or even shorter:
Upload::destroy($id);

Eloquent Join With Pivot Table?

I have a pivot table called message_recipients that looks like
CREATE TABLE `message_recipients` (
`user_id` bigint(20) unsigned NOT NULL,
`message_id` bigint(20) unsigned NOT NULL,
KEY `message_recipients_user_id_index` (`user_id`),
KEY `message_recipients_message_id_index` (`message_id`),
CONSTRAINT `message_recipients_message_id_foreign` FOREIGN KEY (`message_id`) REFERENCES `messages` (`id`),
CONSTRAINT `message_recipients_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
And then I have a messages table
CREATE TABLE `messages` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`sender_id` bigint(20) unsigned NOT NULL,
`subject` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`message` longtext COLLATE utf8_unicode_ci NOT NULL,
`status` tinyint(4) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`deleted_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `messages_sender_id_index` (`sender_id`),
CONSTRAINT `messages_sender_id_foreign` FOREIGN KEY (`sender_id`) REFERENCES `users` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=110 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
And the default user table.
And I have the following classes
class MessageRecipients extends Eloquent {
protected $table = 'message_recipients';
public $timestamps = false;
public function message() {
return $this->hasMany('App\Models\Message');
}
public function user() {
return $this->belongsTo('App\Models\User');
}
public function me() {
return $this->belongsTo('App\Models\User');
}
}
class Message extends Eloquent {
public function recipients() {
return $this->hasMany('App\Models\MessageRecipients');
}
public function sender() {
return $this->belongsTo('App\Models\User');
}
}
And I am trying to figure out how to generate the query. I have
$message = Message::with('App\Models\MessageRecipients')->where('message_recipients.user_id', '=', 1)->first();
But I keep getting an error about missing message_recipients column. How can I generate a query that would look like (or produce the same data as)
SELECT
*
FROM
messages
JOIN
message_recipients
ON
messages.id = message_recipients.message_id
WHERE
message_recipients.user_id = 1
Or basically select all the messages with message_recipients data that are assigned to that user.

Class table inheritance in Yii framework using MySQL views

I would like to implement class (multi) table inheritance in Yii but i found it very difficult, so i planned to use the approach of MySQL view.
Here is an example of my tables and classes:
CmsAd is a table that inherits all the fields included in CmsContent table:
CREATE TABLE `CmsAd` (
`Id_CmsAd` varchar(32) NOT NULL,
`Image` varchar(300) DEFAULT NULL,
`Id_PrdClass` varchar(32) DEFAULT NULL,
`Id_PrdCatalog` varchar(32) DEFAULT NULL,
PRIMARY KEY (`Id_CmsAd`),
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE `CmsContent` (
`Id_CmsContent` varchar(32) NOT NULL,
`ModifiedBy` varchar(32) DEFAULT NULL,
`ModifiedOn` datetime DEFAULT NULL,
`CreatedBy` varchar(32) DEFAULT NULL,
`CreatedOn` datetime DEFAULT NULL,
`Status` varchar(99) DEFAULT NULL,
`Subject` varchar(350) DEFAULT NULL,
`Text` longtext,
`KeyWord` varchar(300) DEFAULT NULL,
`Code` varchar(340) DEFAULT NULL,
PRIMARY KEY (`Id_CmsContent`),
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CmsAd_View is a MySQL view that contains the join of those two tables :
CREATE VIEW `CmsAd_View` AS SELECT `CmsAd`.*, `CmsContent`.* FROM `CmsAd` LEFT JOIN `CmsContent` ON `CmsContent`.`Id_CmsContent` = `CmsAd`.`Id_CmsAd`;
Here are the models of those tables :
class CmsAd extends CActiveRecord {
public function tableName() {
return 'CmsAd_View';
}
}
class CmsContent extends CActiveRecord {
public function tableName() {
return 'CmsContent';
}
}
Notice that the table name of CmsAd is the view CmsAd_View.
Now I would like implement the CRUD the CmsAd. It's ok with find() method because it retrieves from the view CmsAd_View.
My Problem is with insert() and update() methods where we have to insert and update both tables CmsAd and CmsContent.
Is there any one who tried to implement the view approach of table inheritance in Yii ?

Categories