Relationship support in Lithium aka li3

So now some of the relationship support has been there in lithium's x-relationships branch . I was talking with Howard Lince and Nateabele about the progress in relationships .

You can see the updated roadmap here .

So lets start playing with relationships right ?

Currently we have

1 ) hasOne => 1 to 1

2 ) hasMany = > 1 to N

3 ) belongsTo => N to 1 or 1 to 1

4 ) HABTM work in progress

Eg 1 : A user has one profile . hasOne

Eg 2 : A user has many posts

Eg 3 : A user has many comments

Eg 4 : Single or many comments belongs to user .

Eg 5 : A single or many posts belongs to user .

Currently as the work for relationships is in progress I cannot point you to http://lithify.me/docs. But Cake PHP has good documentation of the concepts. You can read it from cakephp

I am going to show only some snippets of code how to create relationships. Once you have done with it , you will be a master.

Note :The command "li3 create model" previoulsy was creating models as singular. But from now onwards its Plural, so the command may be creating singular named file. So you need to do the necessary changes , will be fixed soon before 1.0 release.

We are moving to x-relationships branch. ie

$git checkout x-relationships

What I am going to show is relationship with user and post and user with comments. I assume only registered users can add posts and comments .

So lets dive into it .

Below is the table structure

Now you want to create Comments , Posts , Users models in your app/models folder .

Comments are posted for a particular post by a user .

So we are relating it via variable belongsTo . It must be public.

The $_schema is the array which is the same order the fields are created in table.

The $validates array contains the validations needed.

A user can post many comments and posts . Here in hasMany we have shown the relationship to the other .But its not needed as lithium is smart enough to know your foreign key relationships if you followed it.

Lithium uses filters. Filters are essentially an efficient way of introducing event-driven communication between classes in your application. You can read over filters .

So in your controllers action , you can fetch data like the below.

The Post::find() fetches the post of that particular id and the user who posted it .The Comments::find() fetches the comments and the user who posted it .

If you are storing the users name , email etc in comments table and not like the one I showed then the best way is to add Comments also to the with in Post::find()

A print_r for $post->data() will show the values. You can use a filter to check whether a query is fired and dump the query.

Add the below code in bootstrap.php

Thanks to Nate Abele , Howard and all my #li3 friends who helped me to make this post.

You can see the whole things over https://github.com/harikt/li3_tests . More experiments will be added to it :) .

Tags: 

Comments

Add new comment