Load Model With Related Model By Conditions


(Konapaz) #1

Hi All

I have a Model related with another Model.

I want to get all Records of first Model with the second one.

The second one must be null when a specific condition not satisfied but the first Model have to load normally

for example


$models= Product::model()->with(array(Content'=>array('condition'=>'lang=1')))->findAll(array('condition'=>'enabled=1')

With above code the Models not loaded when the condition of second not satisfied.

I want to Load all enabled Products and only their Content that has lang=1 else Content set to Null

Something Like


LEFT OUTER JOIN ON (... AND 'lang=1') WHERE enabled=1 

and not


LEFT OUTER JOIN ON (...) WHERE enabled=1 AND lang=1

Also I have a suspicious that the eager loads the content when $models->content called…

How achieve those things ?

Many thanks!


(Mmbalasundaram) #2

try this one

http://www.bsourcecode.com/2012/12/findall-in-yii.html#yii-findall-join


(Konapaz) #3

I found the solution by parameter on


$models= Product::model()->with(array(Content'=>array('on'=>'lang=1')))->findAll(array('condition'=>'enabled=1')

I have an issue (As I excpected)

Although the second Model does not loaded as I want (I checked by var_dump), when I Call Protuct->content the Content is auto loaded.

How can prevent this?

Ok I had missed a parameter in another part of code, now everything works ok!

So the solution for my issue is the parameter on in "with".

Thank @mbala for your response :)