Currently i'm having a problem. I want to access the data available in the 4th table of my DB.
Db image:
I have the tables in this way: Categories --> Categories_Companies --> Companies --> Affiliates
Like it shows in the image i'm on the categories and in the Categories view (views/categories/view.ctp) i want to show the fields title and url from the affiliates table.
There is another way of doing that without using the this->query?
Regards
You access a table through its model. The Category model is automatically included in the CategoriesController by naming convention. You can include other models by using $uses.
var $uses = array('Category', 'Affiliate');
function view() {
$this->Category->find(…);
$this->Affiliate->find(…);
}
Or, if your models are linked through associations, you can access them through an association:
$this->Category->Company->Affiliate->find(…);
Both examples are equivalent, the first is just more convenient.
Related
In a Silverstripe (version 3) model admin, how can I get the collection of fields from a different model so as to add them to this model's admin?
I have tried this using FieldList::addFieldsToTab:
$loremIpsumTab = Tab::create('LoremIpsum');
$fields->fieldByName('Root')->insertAfter('Main', $loremIpsumTab);
$loremIpsumFields = (
$this->LoremIpsum()->getCMSFields()
->fieldByName('Root.Main')->Fields());
$fields->addFieldsToTab('Root.LoremIpsum', $loremIpsumFields);
That creates the tab correctly, but moves the fields incorrectly: all the fields from 'Root.Main' are moved, not only those for the LoremIpsum model.
I had assumed this would interrogate the related LoremIpsum model for its CMS fields:
$this->LoremIpsum()->getCMSFields()
->fieldByName('Root.Main')->Fields()
So how can I move only those fields for the LoremIpsum model?
Hello and welcome to StackOverflow. What do you want to acchieve?
It seems you want to edit a has_one relation dataobject from your other dataobject. There are ready-to-use and tested modules for this scenario, e.g. https://github.com/stevie-mayhew/hasoneedit/tree/3.x , cause even if you manage to display the fields, SilverStripe assumes those values belong to the current model and not to a relation. Then you'll have extra work to save it back etc...
Some fields in your current model and in the LoremIpsum model have the same name, e.g. ID, Title, Created. This causes problems in your code above, cause you can only have one Field for e.g. ID in a Form.
The "hasoneedit" module overcomes this by prefixing the relation's fields.
How should I name the tables and models for user category and article category? I have two tables one users and the other articles. I want to categorize these so that I can for example just call the news articles or use just users that are in the company category. So I need relationships between these models/tables.
I thought about to use a single table and a single model for both article and user but these two don't have much in common plus that could be a problem when I'll bind the relationships between them.
Laravel uses the singular style naming for pivot table, I don't want to break that. So I can't use singular names for these as well. My current choice is:
Article --> main model
articles --> main table
ArticleCategory --> relational model
articles_categories --> relational table
--------------------------------------
User --> main model
users --> main table
UserCategory --> relational model
users_categories --> relational table
So what do you think? Should I use this way or is there a better way to go?
Using a Eloquent Model you can set table name for your particular model.Simple example for User model is as below:-
class User extends Eloquent {
protected $table = 'articles';
}
check this Eloquent you can easily understand. Thanks
best way is:php artisan make:model User -m
with this way laravel create model and migration name and file automatically
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I need to develop a custom form generator using Laravel.
That means there will be a GUI to select and customise the forms like Registration Form or Booking Form.User should be able to add/edit/delete different form controls, define it as mandatory, etc.
Here I am little confused to handle this in back-end. What is the better way to achieve this?
Or how can I implement a database architecture to use some metadata table which can be used to handle multiple items like Wordpress and is there any built-in Laravel functionalities to handle these meta objects?
And how the insert/update/delete handled in this metadata approach?
Here an insert should have only one row in the meta table. Suppose at the time of user registration, without saving the firstname and lastname in separate rows in the meta table, it should use some objects like this in a single row.
a:3:{s:9:"firstname";s:10:"irshad.far";s:8:"lastname";s:0:"";s:5:"_meta";a:7:{s:2:"ip";s:10:"14.99.80.3";s:9:"confirmip";s:10:"14.99.80.3";s:11:"confirmtime";d:1407932201;s:8:"signupip";s:10:"14.99.80.3";s:10:"signuptime";d:1407932201;s:4:"lang";s:2:"en";s:4:"form";s:7:"unknown";}}
Handling a table of meta data is fairly straight forward using Laravel's Eloquent relations. Let's say you have a users table in your database that contains:
id email password created_at updated_at deleted_at
If you want to keep it simple and not add all sorts of extra data to your users table you could create a meta table and then a link table user_meta to relate the two.
But what if you also have a posts table (as with Wordpress) and your posts also need meta data? Instead of also creating a posts_meta table to link your posts to their meta, we can use Laravels Eloquent relations and create some Polymorphic Relations.
The Database
Here's our setup, along with our users table (above) we have a posts table which has the fields:
id title content created_at updated_at deleted_at
We also have our meta table that follows the guidelines for a polymorphic relation:
id name value metable_id metable_type
//int meta key meta value post/user id resource ie post/user
Using this we could add meta for a post or user to our meta table like this:
id name value metable_id metable_type
------------------------------------------------------
1 nickname Steve 1 User
2 author Steve O 1 Post
All we need to do to grab this info from the database is define the relations in our respective models.
The Models
So now we have our DB ready we need to setup our models (one model for User, one for Post and one for Meta) with our polymorphic relationship. Our User and Post models are both going to use the same function to relate to our Meta model:
User.php
========================================
class User extends Eloquent {
public function meta()
{
return $this->morphMany('Meta', 'metable');
}
}
Post.php
========================================
class Post extends Eloquent {
public function meta()
{
return $this->morphMany('Meta', 'metable');
}
}
Now we define the inverse of those relations in our meta model:
Meta.php
========================================
class Meta extends Eloquent {
public function metable()
{
return $this->morphTo();
}
}
That's it!
Getting the data
Now all you need to do to get at the meta data for a user or post is:
// Load in a post with an id of 1 and get all it's related meta
$post = Post::find(1);
$meta = $post->meta;
If we were to return the meta object we might see something like:
[{"id":2,"metable_id":1,"metable_type":"Post","name":"author","value":"Steve O"}]
Onwards!
From here you can create helper functions like this one that checks if the meta you're after exists in the results:
public function hasMeta($key)
{
$meta = $this->meta;
foreach ($meta as $item):
if( $item->name == $key ) return true;
endforeach;
return false;
}
// Use it like:
if($post->hasMeta('author')){
// Display author
}
Read more about Laravels Eloquent relationships in the docs here: http://laravel.com/docs/eloquent-relationships
I once did something similar, my approach was to build a mini DB engine where forms are like tables and data is rows:
A form which describes the structure and design of a form:
Form {
id,
title,
layout,
...
}
Fields of the form with types and validation rules
Field {
formId,
name,
type (String, Date, Image, Integer, Double, List, ...),
pattern (Regex validation maybe),
...
}
Inserted data in a form is a row belonging to that form
Row {
id,
formId,
}
Each row is a group of entries to fields of the corresponding form that can be validated following the predefined rules.
Entry {
rowId,
fieldId,
value
}
Type and rules can be regrouped in another object so you can have dynamic types that you can manage.
Lists can have another object that stores choices and type of list (multi-select, mono-select)
Metadataobjects itself would be saved in one table. But performance-wise I think those object should their own data tables.
Approach 1)
These types of forms needs to be predefined and linked to a specific controller. This must be either so that there is only one controller for each type of form like Registeration, and only one user defined metadataobject can be in use at either time. This controller's table parameter would be set to point to a database table created specifically for that metadataobject (or perhaps same table could be migrated according to metadata but then that table should be empty).
Or 2) every metadataobject should have it's own controller created which points to the object's data table.
In each approach routes needs to be created to point to the one controller of each type at use in each time.
One dilemma is how to manage revisions of those objects. Perhaps each object might have a running number postfix, and have their own controllers and data tables created (then it might be easier to migrate even populated tables [then user would be notified on front-end if his action would result in data loss, like for example with deleting a form data field]).
Another part of this project is to create an intelligent generator engine for assembling the HTML, CSS, and JS code according to a metadataobject. The generated code can be saved to reside in the same table as the objects themselves, and when used should be cached in the backend for rendering views.
Such metadataobject must itself have a clever format, so that it composes of predefined pieces of settings which will be converted to functionality by the form generator code.
I have managed to join 2 of my tables clients and risk_codes to each other where clients.risk_code_id is a foreign key for risk_codes.id.
In my edit view for Clients I ouput a form using the HTML Helper. E.g. to add an input to edit clients.name I would use echo $this->Form->input('name');
Given that risk_codes is a separate table/model how would I output a select dropdown with the options being risk_codes.name and the values being risk_codes.id?
The tables are linked like so:
Client belongsTo RiskCode
RiskCode hasMany Client
In your RiskCode model make sure that displayField is either set to null or name (the latter is one of the defaults):
public $displayField = 'name'; // or null;
In the controller set a list of risk codes for the view:
$this->set('riskCodes', $this->Client->RiskCode->find('list'));
And in the view simply reference the appropriate foreign key field name:
echo $this->Form->input('risk_code_id');
CakePHP will automatically create an appropriate select list, using the models id and displayField field values from the list set as riskCodes.
ps. Many questions like this are answered in the Cookbook, and can also be figured out by using CakePHP to bake the controllers and views.
I'm quite new to CakePHP so I'm wondering if anyone can help me with how to order my pages.
I have a table of products (with a Product model and products_controller).
I also have a table of categories (with a Category model and categories_controller).
The categories hasMany products.
Firstly, is the name categories incorrect to call it. According to CakePHP convention, what is the correct name to call it?
Secondly I would like the user to click on the products link and then be presented with a list of categories and finally, once he/she chooses a category be presented with the products in that category. How would this be laid out?
You're asking some pretty basic CakePHP stuff, I suggest you read the book, which outlines naming conventions, file structure and data retrieval to name a few things.
That being said, the name categories is correct, unless you want products to have more than one category, the relationship will be Product 'BelongsTo' Category.
To get category info inside the product controller you can just access it's find methods with $this->Product->Category->find();, but again I recommend you read through the CakePHP book as you go to build up our knowledge and learn more about the framework you're using.
You mean that categories is not a plural of category? I think so. Your table has to be named as 'categories'.
Secondly, I think that you need a Categories hasAndBelongsToMany Products (HABTM) in your model, so every Category has many Products, and also a Category belongs to many products.
Use the 'cake bake' command and you will see easily if it is what you want.
Hope it helped, althought I'm quite new in cakePHP as well...
Alf.
If you have categories tables in db, its controller would be categories_controller.php and the Products belongsTo Category will work if products belong to only one category. No need to HABTM relationship. See in cakephp the model files are in singular form and controller file are in plural form with controller attached with them. The tables are named in plural in db.
Regarding ur 2nd question, I think im not getting it exactly.