Laravel:返回非关系模型数据

时间:2016-05-15 16:08:22

标签: laravel

我有Character模特。一个Character可以进化,如果Evolution可以进化,我想返回Character(以及字符数据)。

我在Character模型中执行此操作:

public function evolution() 
    {
    return Evolution::where('character_id' , '=', $this->id)
            ->where('level', '<=', $this->level)
            ->first();
}

问题是我正在尝试使用With查询keywoord(用户模型)返回它并且它根本不是关系:

$userCharacters = UserCharacters::with('character')
        ->with('evolution')
        ->where('user_id','=',$this->id);

如何在不使用UserCharacterForEach模型中手动添加“Character的情况下,与 using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Configuration; using System.Linq; using System.Web; using System.Collections; namespace Website { public static class ConnectionClass { private static SqlConnection conn; private static SqlConnection command; static ConnectionClass() { string connectionString = ConfigurationManager.ConnectionStrings["tigariConnection"].ToString(); conn = new SqlConnection(connectionString); command = new SqlCommand("",conn); } public static ArrayList GetTigariByType(string tigariType) { ArrayList list = new ArrayList(); string query = string.Format("SELECT * FROM tigari WHERE type LIKE '{0}'", tigariType); try { conn.Open(); command.CommandText = query; SqlDataReader reader = command.ExecuteReader(); while(reader.Read()) { int id = reader.GetInt32(0); string name = reader.GetString(1); string type = reader.GetString(2); double price = reader.GetDouble(3); string country = reader.GetString(4); string image = reader.GetString(5); string review = reader.GetString(6); Tigari tigari = new Tigari(id, name, type, price, country, image, review); list.Add(tigari); } } finally { conn.Close(); } return list; } } } 一起输出演变?

2 个答案:

答案 0 :(得分:0)

您可以尝试使用原始查询。

即,

DB:table('usercharacters')
->join('character','usercharacter.id','=','character_id')
->join('evolution','usercharacter.id','=','evolution_id')
->where('your_where_clause')
->first();

答案 1 :(得分:0)

将函数转换为关系式:

public function evolution() 
{
    return $this->hasOne(Evolution::class,'character_id')->where('level', '<=', $this->level);
}