Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Many-to-many relationship model
  • Hi there,

    I'm a complete beginner with PHP frameworks and have basic knowledge of both PHP and the MVC model. I want to create a simple system with FuelPHP following this database schema. The functions of the system will be as follows:
    1) Adding/removing/editing 'books' by the administrator.
    2) Users 'subscribing' and 'unsubscribing' to and from 'books' respectively. Of course, logging in and out is assumed.

    I've read and/or followed these tutorials:

    After a lot of trying, this is what I've accomplished so far:
    1) Create an Admin template for adding/removing/editing/viewing books. This includes logging in and out.
    2) Created the inter-table between users and books to support the many-to-many relationship. I used the 'generate model' command. If it is better to use the manual method, please tell me why. I then deleted the auto-generated 'id', 'created at' and 'updated_at' fields from the model as well as the database.

    Some questions:
    1) I need to take the many-to-many relationship into consideration in the model file. Can you check if my model file at model/books/user.php is correct? I've pasted it here. My project file structure can be viewed over here.
    2) The query to retrieve the books a user has 'subscribed' to has to be defined in a controller, yes? If so, which controller? Or do I have to create a new controller?

    Thanks for your time.
  • HarroHarro
    Accepted Answer
    1. Your relation definition looks ok.

    2. That depends.

    There are basically two schools of thought. One that says that the ORM is the model, and therefore Model method calls are done in the controller (you'll see this in most examples, it is the largest group), and one that says that the ORM is just an abstraction layer, and you need another Model between an ORM model and the controller.

    i'm with the second group. You should keep your controllers as lean as possible, only use them to "control", not for business logic.

    So I would have a User Model (which in this case would extend ORM, because there is a single relation between the User entity and the database table), and I would add a method get_books(), that would return an array of Book models. Your controller will just do

    $subscribed = Model_User::get_books();

    It does not need to know what the logic is to retrieve that, that is the task of the model.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion