繁体   English   中英

多对多关系Laravel 4

[英]Many to Many Relationship Laravel 4

我正在研究laravel-4应用程序。 目前,它很好地融合在一起,并且我一直在努力定义数据库的各个表之间的关系。 但是,我遇到了无法解决的问题。

在我的数据库中,有一个资源表和标签表。 它们之间有很多对很多的关系,所以我也有一个resource_tags表,其中两个表的id作为foreign keys

现在,当我根据用户通过表单提供的数据创建资源时,我将创建资源,检查类型并决定操作。 然后,我检索资源的标签并遍历它们,并在“ Tags表中创建一个条目。

我的问题是将信息放入resource_tags表。 有没有一种方法可以使我相对轻松地执行此操作?

这是我的controller ,正在处理表单提交:

class SharedResourcesController extends BaseController {
    //Add a shared Resource to the DB
    //To do: Error checking and validation. 
    public function handleResource(){

        //Create Object
        $resource = new SharedResource;
        $resource->title = Input::get('title'); //Title of resource
        $resource->user_id = Input::get('user_id'); //User who uploads
        $resource->book_id = Input::get('book_id'); //Book it is associated with
        $resource->type_id = Input::get('type_id'); //Type of resource

        //STORE LINKS
        //if type is link... 1
        if($resource->type_id == "1"){
            $resource->web_link = Input::get('link');
        }
        //if type is video...2
        if($resource->type_id == "2"){
            $resource->vid_link = Input::get('link');
        }
        //UPLOADING
        //If type is doc...3
        if($resource->type_id == "3"){
            if(Input::hasFile('file')){
                $destinationPath = '';
                $filename = '';
                $file = Input::file('file');
                $basename = Str::random(12);
                $extension = $file->getClientOriginalExtension();
                $destinationPath = public_path().'/file/';
                $filename = Str::slug($basename, '_').".".$extension;//Create the filename
                $file->move($destinationPath, $filename);
                $resource->doc_link = $filename;
            }
        }
        //if type is img...4
        if($resource->type_id == "4"){
            if(Input::hasFile('file')){
                $destinationPath = '';
                $filename = '';
                $file = Input::file('file');
                $basename = Str::random(12);
                $extension = $file->getClientOriginalExtension();
                $destinationPath = public_path().'/img/uploads/';
                $filename = Str::slug($basename, '_').".".$extension;//Create the filename
                $file->move($destinationPath, $filename);
                $resource->img_link = $filename;
            }
        }

        //TAGS 
        //Get the tags
        $tags = Array();
        $tags = explode(',', Input::get('tags'));
        foreach($tags as $tag){
            //Create a new Tag in DB - TO DO: Only Unique TAGS
            $newTag = new Tag;
            $newTag->name = $tag;
            $newTag->save();
            //Enter to resource tags
        }

        //Entry to resouce_tags

        //Save Object
        $resource->save();
        return Redirect::action('User_BaseController@getSharedResources')->with('success', 'Resouce Created!');

        //Any errors return to Form...
    }
}

MODELS

class SharedResource extends Eloquent{
    //set up many to many
    public function tags(){
        return $this->belongsToMany('Tag');
    }

class Tag extends Eloquent{
    //set up many to many
    public function sharedResources(){
        return $this->belongsToMany('SharedResource');
    }

我知道在验证和错误处理方面有很多遗漏,但是我只是想使流程正常工作,我可以在以后进行修改。 我将不胜感激。

您所需要做的就是构建或获取资源,然后构建或获取标签,然后在资源的标签关系上调用saveMany并将一组标签项传递给它,如下所示(伪代码示例):

$resource = Resource::create(['name' => 'Resource 1']);
$tag = [];
for ($i = 5; $i > 0; $i--) {
    $tag = Tag::create(['name' => 'Tag '.$i]);
    array_push($tags, $tag);
}
$resource->tags()->saveMany($tags);

$ tags必须是Tag对象的数组,在关系上调用的saveMany将为您处理数据透视表的插入。 您应该最终在资源表中获得资源1资源,在标签表中获得五个标签,在resource_tag表中获得5条记录并保存关系。

您是否也可以为两个模型添加代码? 您是否在其中定义了关系?

例如:

class Resource  extends Eloquent {

    public function tags()
    {
        return $this->belongsToMany('tag');
    }
}

class Tag  extends Eloquent {

    public function resources()
    {
        return $this->belongsToMany('resource');
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM