【发布时间】:2016-06-06 08:54:02
【问题描述】:
我正在尝试在 laravel 中实现多态关联,但它没有显示结果或错误。
餐桌:
CREATE TABLE IF NOT EXISTS `posts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`content` varchar(255) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `posts` (`id`, `name`, `content`, `created_at`, `updated_at`) VALUES
(1, 'php post', 'Php mysql javascript', '2016-06-06 07:16:49', '0000-00-00 00:00:00'),
(2, 'node', 'express node js', '2016-06-06 07:16:49', '0000-00-00 00:00:00');
CREATE TABLE IF NOT EXISTS `taggables` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`taggable_id` int(11) NOT NULL,
`tag_id` int(11) NOT NULL,
`taggable_type` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `taggables` (`id`, `taggable_id`, `tag_id`, `taggable_type`) VALUES
(1, 1, 1, 'Post'),
(2, 2, 2, 'Video');
CREATE TABLE IF NOT EXISTS `tags` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
INSERT INTO `tags` (`id`, `name`, `created_at`, `updated_at`) VALUES
(1, 'ruby tag', '2016-06-06 07:20:00', '0000-00-00 00:00:00'),
(2, 'javascript tag', '2016-06-06 07:20:00', '0000-00-00 00:00:00'),
(3, 'rails tags', '2016-06-06 07:20:25', '0000-00-00 00:00:00');
另一个表是视频
型号
<?php
//Post.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model {
public function tags()
{
return $this->morphToMany('App\Tag', 'taggable');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model {
public function posts()
{
return $this->morphedByMany('App\Post', 'taggable');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model {
public function posts()
{
return $this->morphedByMany('App\Post', 'taggable');
}
}
class PostController extends Controller {
function index () {
$id = 1;
$a = Post::all();
return view('Pages.index',compact('a'));
}
}
查看
<table>
<tr>
<td width="100px">Id </td>
<td>Name</td>
</tr>
<?php foreach ($a as $value) { ?>
<tr>
<td>
<?php print_r($value->id);?>
</td>
<td>
<?php print_r($value->name);?>
</td>
<td> <?php dd($value->tags()); ?>
<td>
</tr>
<?php } ?>
<table>
相关数据未显示 :( 鉴于此,请查看此内容并让我知道我错在哪里
【问题讨论】:
标签: php laravel associations