Cakephp hasMany and belongsTo with example

CakePHP offers excellent way for associations for linking models. There are 4 types of relationship in CakePHP which are as below.

1) hasone is used for One to one relationship.
2) hasMany is used for one to many relationships.
3) belongsTo is used for many to one relationship.
4) hasAndBelongsToMany is used for many to many relationship.

Cakephp Associations Linking Models  Relationship Types with example

Cakephp Associations Linking Models Relationship Types with example

Have a look on the example and explanation of hasMany and belongsTo relationship.

Example

This example is useful to understand Category and Product relationship in cakephp.

Category table have two fields “id” and “CategoryName”.

Product table have three fields “id”, “category_id” and “ProductName”. You can add as many fields as you want in product table but I took only 3 to explain the relationship with category.

 
class Category extends AppModel {
    public $order = "CategoryName";
 
    public $hasMany = array(
        'Product' => array(
            'className' => 'Product',
            'foreignKey' => 'category _id',
            'dependent' => true
        )
    );
}

In the Category model class, each category have either one or more than one products. when you are doing association like this than you have to use “hadMany” relationship in CakePHP. I define that “category_id” is a foreignkey in product table. Example of CakePHP “hasMany” relationship type.

 
class Product extends AppModel {
    public $order = "ProductName";        
 
    public $belongsTo = array(
            'Category' => array(
                'className' => ' Category ',
                'foreignKey' => 'category_id'
            )
        );
}

In the Product model class, each product belongs to any one category. I define that “category_id” is a foreignkey in product table. Example of CakePHP “belongsTo” relationship type.

Many developer confuse here and try to use CakePHP “hasOne” relationship type in product model class which will not work at all. I hope that, this example is useful to clear your confusion about the CakePHP relationship types.

how to enable mod_rewrite on iis server for php pages

Recently, I am working with one project which is hosted on the windows IIS server. I used .htaccess for URL rewrite rules for SEO(Search Engine Optimization) purpose.

I see that its not working on the IIS while it is working perfect on my local apache server. I see that may be URL Rewrite module may not be installed on the IIS server.

After looking on the IIS configuration, I knew that URL Rewrite module is installed but its not working similar to apache mod_rewrite. I need to enable mod_rewrite on IIS server same way its works in Apache server. After spending lots of time, I found the solution for this.

I will show you simple way using that you can get similar functionality like Apache on IIS Server.

You need to create web.config file in your root directory using below code.

Your web.config file code to test:

 
	<?xml version="1.0" encoding="UTF-8"?>
	<configuration>
		<system.webServer>
			<rewrite>
				<rules>
					<clear />
					<rule name="Redirect to google.com" stopProcessing="true">
						<match url="^google$" />
						<action type="Redirect" url="http://www.google.com/" appendQueryString="false" />
					</rule>
				</rules>
			</rewrite>
		</system.webServer>
	</configuration>

Once you did this than its time to test that its working or not?
To test try to open http://www.domain.com/google in browser where domain.com is your website’s domain name. If you are redirected to Google.com website means your URL rewrite module installed and working same like apache mod_rewrite.

This is just to check that Microsoft URL Rewrite module installed on your IIS server or not, if its installed than change your web.config file with below code:

Your final web.config file code:

 
	<?xml version="1.0" encoding="UTF-8"?>
	<configuration>
	  <system.webServer>
		<rewrite>
		  <rules>
			<rule name="Security Rule" stopProcessing="true">
			  <match url="^(.*)$" ignoreCase="false" />
			  <conditions logicalGrouping="MatchAny">
				<add input="{QUERY_STRING}" pattern="mosConfig_[a-zA-Z_]{1,21}(=|\%3D)" ignoreCase="false" />
				<add input="{QUERY_STRING}" pattern="base64_encode.*\(.*\)" ignoreCase="false" />
				<add input="{QUERY_STRING}" pattern="(\&lt;|%3C).*script.*(\>|%3E)" />
				<add input="{QUERY_STRING}" pattern="GLOBALS(=|\[|\%[0-9A-Z]{0,2})" ignoreCase="false" />
				<add input="{QUERY_STRING}" pattern="_REQUEST(=|\[|\%[0-9A-Z]{0,2})" ignoreCase="false" />
			  </conditions>
			  <action type="CustomResponse" url="index.php" statusCode="403" statusReason="Forbidden" statusDescription="Forbidden" />
			</rule>
			<rule name="SEO Rule">
			  <match url="(.*)" ignoreCase="false" />
			  <conditions logicalGrouping="MatchAll">
				<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" pattern="" ignoreCase="false" />
				<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" pattern="" ignoreCase="false" />
				<add input="{URL}" negate="true" pattern="^/index.php" ignoreCase="false" />
				<add input="{URL}" pattern="(/|\.php|\.html|\.htm|\.feed|\.pdf|\.raw|/[^.]*)$" />
			  </conditions>
			  <action type="Rewrite" url="index.php" />
			</rule>
		  </rules>
		</rewrite>
	 </system.webServer>
	</configuration>

if you get Cakephp : 404 – File or directory not found error on the windows server than please check Microsoft URL Rewrite module installed on your IIS server or not? If not than you need to enable mod_rewrite on iis server to run your cakephp project.

Incoming search terms:

  • enabling php mod_rewrite on IIS 8 5
  • Mod_REwrite IIS PHP

Warning: SplFileInfo::openFile(/app/tmp/cache/persistent/myapp_cake_core_file_map) [function.SplFileInfo-openFile]: failed to open stream: Success in /lib/Cake/Cache/Engine/FileEngine.php on line 357

Recently, I am working with cakephp projects and its working fine in my local server, when i moved to the production server then its give the error which is as below.

Warning: SplFileInfo::openFile(/app/tmp/cache/persistent/myapp_cake_core_file_map) [function.SplFileInfo-openFile]: failed to open stream: Success in /lib/Cake/Cache/Engine/FileEngine.php on line 357

Warning: SplFileInfo::openFile(/app/tmp/cache/persistent/myapp_cake_core_file_map) [function.SplFileInfo-openFile]: failed to open stream: Success in /lib/Cake/Cache/Engine/FileEngine.php on line 357

Warning: SplFileInfo::openFile(/app/tmp/cache/persistent/myapp_cake_core_cake_dev_en-us) [function.SplFileInfo-openFile]: failed to open stream: No such file or directory in /lib/Cake/Cache/Engine/FileEngine.php on line 357

Warning: _cake_core_ cache was unable to write ‘cake_dev_en-us’ to File cache in /lib/Cake/Cache/Cache.php on line 325

Warning: _cake_core_ cache was unable to write ‘file_map’ to File cache in /lib/Cake/Cache/Cache.php on line 325

Fatal error: Call to undefined function error_get_last() in /lib/Cake/Core/App.php on line 913

Basically, when we look error like this then we think that this is a permission issue, same way i go to tmp folder and set permission and make the folder writable. There is no change at all in the error after i set the permission.

After few research i found that might be this is a issue of owner and group, so i look in that and set the owner and group of the tmp folder to apache, but still no change at all.

Since last two days, i am working on this issue and today suddenly i think that let me check it from starting point and looked in the cakephp requirements which is as below

Requirements

HTTP Server. For example: Apache. mod_rewrite is preferred, but by no means required.
PHP 5.2.8 or greater.

Technically a database engine isn’t required, but we imagine that most applications will utilize one. CakePHP supports a variety of database storage engines:

MySQL (4 or greater)
PostgreSQL
Microsoft SQL Server
SQLite

When i check php version on the production server then its 5.1.6 and cakephp 2 require php 5.2.8 or greater.

This is very silly issue but normally we never look on the version when we move the code from local server to production server, make sure when you stuck then look on version.

301 redirect in cakephp (moved permanently in cakephp)

301 redirect in cakephp (moved permanently in cakephp)

How to permanently 301 redirect in cakephp?
Best way for 301 redirect (permanently redirect).
301 redirect without .htaccess file.

Recently, i am working with cakephp project, and my client need to redirect all the old links to new links. As its a ecommerce website, it have the category and products but the old php developer made single page with two parameter in the query string, where one is cid which indicate the category and another one is pid which indicate the product. all the links are not seo friendly and its look like as below

N Numbers of links in the project but i show 3 example where we need to do 301 redirect from old links to new links.

 
 // Old Links
 
  productcategory.php?cid=1&amp;pid=3      // Category and Product Page 
  productcategory.php?cid=5&amp;pid=31     // Category and Product Page
  productcategory.php?cid=22           // Only Category Page
 
 // New Links 
 
  product/1/electronics/3/iphone      // Category and Product Page 
  product/5/games/31/play-station-4    // Category and Product Page
  category/22/beauty/                  // Only Category Page

301 redirecting is not easy and we need to workout with the rewrite rules using .htaccess file but i did it with easily in CakePHP. In cakephp 301 redirect like this is possible without .htaccess file. you need to create the productcategory.php in your webroot folder and place below code in that.

 
 <?php
 
	$siteurl = "http://www.freelancephpdevelopment.com/";
	$cid = isset($_GET['cid']) ? $_GET['cid'] : '';
	$pid = isset($_GET['pid']) ? $_GET['pid'] : '';		
 
	switch($cid)
	{
		case '1':
				$CategoryName = "electronics";
				break;
		case '5':
				$CategoryName = "games";
				break;
		case '22':
				$CategoryName = "beauty";
				break;
	}	
 
	switch($pid)
	{
		case '3':
				$ProductName = "iphone";
				break;
		case '31':
				$ProductName = "play-station-4";
				break;		
	}
 
	if($cid != '' && $pid != '')
	{
		header("HTTP/1.1 301 Moved Permanently"); 
		header("location: ".$siteurl."product/".$cid."/".$CategoryName."/".$pid."/".$ProductName);
		exit;
	}
	else if($cid != ''){
		header("HTTP/1.1 301 Moved Permanently"); 
		header("location: ".$siteurl."category/".$cid."/".$CategoryName);
		exit;
	}
	 else {
		header("HTTP/1.1 301 Moved Permanently"); 
		header("location: ".$siteurl);
		exit;
	}

After reading my article, I hope that you can resolve your 301 redirect cakephp issue. still you are facing any issue then please let me know and i will be happy to help you.